Question threading

andrews

Well-known member
Joined
Nov 22, 2011
Messages
132
Programming Experience
5-10
Hi,
I am totally new in threadings.
Normally, without threading, when I do calculations I want to see the intermediate results during the calculations.
Therefor I use the method :


For keer = 1 To 40000000
If keer Mod 2000 = 0 Then
Application.DoEvents() Form1.Label2.Text = minsom.ToString & " " & keer.ToString
End If
...
...
next


But when I set the subroutine in a thread I see no change in the label.
My question, why and what can I do?
Thanks for any response
 
Hi,

Threading and multi-thread applications are a big topic and one of the best places to start with learning to use threads is to read up on the BackgroundWorker (BGW) Class. Have a look here:-

BackgroundWorker Class

To do what you are demonstrating there using a BGW you would do all your work in the DoWork Event of the BGW which executes on a Worker thread and then pass the “keer” value to the ReportProgress Method of the BGW. This then raises the ProgressChanged Event on the UI Thread which then allows you to update controls on the UI thread while your application continues to run in the background.

This is just one of the correct ways to update user controls from a worker thread and I suspect that the reason why yours is not working at the moment is that you are not following the rules of threading which basically say:-

When a thread other than the creating thread of a control tries to access one of that control's methods or properties, it often leads to unpredictable results. A common invalid thread activity is a call on the wrong thread that accesses the control's Handle property

Have a look here for more information:-

Control.CheckForIllegalCrossThreadCalls Property:-

Hope that helps.

Cheers,

Ian
 
You can create a delegate and point it to a method that does the UI updates, easy in .Net 4:
Dim displayProgress = Sub(a, b) Label2.Text = String.Format("{0} {1}", a, b)

Then in worker thread use Control.Invoke to call the delegate in the controls thread:
Label2.Invoke(displayProgress, minsom, keer)
 
Back
Top