Gareth Antony Fowell Gareth Antony Fowell - 2 years ago 85 Question

Multi-Threading Glitch

I have a program that uses a label called

and a textbox called

The gist is that if the
Variable = 0
then the label colour is gray,
If the
Variable = 1
then the label uses a thread which flashes between gray and red.

This works almost perfectly apart from if changing between the two values very quickly (entering 0 then deleting it then entering 1, and so on) Then the thread speed increases (as if it is multi-threading).

The strange thing is that if swapping between the values 0 & 1 slowly (every 2 seconds +), then it doesn't increase the blinking speed (this is what the program needs to do)

This is expanded code from the following question: multi threading

Note: This is just a VB.NET conversion from my project on VisiWin.NET. In this example the TextBox
will be an actual variable read from a PLC and the label
will be triangles representing a process solenoid from a process flowsheet mimic. Every solenoid will be controlled by different variables.

Imports Microsoft.VisualBasic
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Threading
Imports System.Diagnostics

Public Class Form1

Private _flash As Boolean = False

Private Sub Variable1_TextChanged(sender As System.Object, e As System.EventArgs) Handles Variable.TextChanged

If Variable.Text = "1" And Not _flash Then
_flash = True
Dim FlashThread As New Thread(New ThreadStart(AddressOf FlashLabel))
End If

If Variable.Text = "0" Then
_flash = False
Valve.ForeColor = Color.Gray
End If

End Sub

Private Sub FlashLabel()

Dim _Color As Color = Color.Gray
While _flash

If Valve.ForeColor = _Color Then
Valve.ForeColor = Color.Red
Valve.ForeColor = Color.Gray
End If

End While

End Sub

End Class

Answer Source

The problem is the following:

  1. You enter 1, _flash is False: The thread is started, changes the color and sleeps 2 seconds
  2. You enter 0 quickly after entering 1, _flash is True: _flash will be set to False.
  3. You enter 1 quickly after entering 0, _flash is False again: A new thread is started.

Now, if steps 2 and 3 happen while the first thread sleeps, you have two running threads. After the first thread is finished sleeping, it will see that _flash is True and will continue running.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download