I am working on an application where two threads execute a method from a class simultaneously. This method performs some complex calculations and the result is displayed in a WinForm.
So my class looks like:
class Comp_func
{
/* Constructor */
public Comp_func()
{
}
public void THE_Complex_func(string One, Int16 Two, Int32 Three)
{
Calculate_this(One);
Thread.Sleep(10);
Calculate_that(Two);
Thread.Sleep(10);
Calculate_thatThat(Three);
Thread.Sleep(10);
Update_lable_in_form(value);
Thread.Sleep(10);
}
}
Each thread updates different Label in the WinForm so, I expect no issues about thread synchronization (as I have used Thread Safe Methods).
My need is those updates should occur simultaneously (at least seem to occur simultaneously).
When the user clicks on a “Calculate” button in my form, I do:
Comp_func Func1_class = new Comp_func();
Comp_func Func2_class = new Comp_func();
Thread Func1_Thread = new Thread(() => Func1_class.Start_Test("Blah", 2,3));
Thread Func2_Thread = new Thread(() => Func2_class.Start_Test("BlahBlah", 4,5));
//Func1_Thread.Priority = ThreadPriority.Highest; /* Deleted after Comments */
// Func2_Thread.Priority = ThreadPriority.Highest; /* Deleted after Comments */
Func1_Thread.Start();
Func2_Thread.Start();
/*
// Removed after Comments
// Let only Threads Run
while(true)
{
Application.DoEvent();
Update();
}
for(count = 0; count < 100; count++)
{
console.WriteLine("I WON'T USE WHILE(1) loops with DOEVENTS");
}
*/
My problem is that when execution of Thread 1 completes, it updates the Label, and then Thread 2 starts and executes.
In order to avoid this behavior, I wrote Thread.Sleep(); after almost each line. It still behaves as if windows did not take care of switching!
Any idea why this is happening?
Thanks in Advance!
Your code example is quite incomplete – so it is difficult to see what is going on.
the first comment I would have is that you should not have an infinite loop in your click handler – in fact you shouldn’t need the
while(true)..DoEvent()code at allIn response to your requirement that the two labels update simultaneously the best thing to do is have the threads join before updating the UI – one method to do this would be to create a BackgroundWorker that kicks off the other two threads, Join()s them, then updates the UI with the two results – depending on the version of .net you are running you may be able to use the Tasks library to do it with less code.
here is a rather crude implementation (if you don’t have the Tasks library available):