Translate

jueves, 23 de enero de 2014

C# and MultiThreading

This is an example of how to implement multi-threading using .Net and C#. This application launches a method called DoWork in two different threads. This would cause that we are not going to have a established order. They could do in an apparently random way.

The method uses a While do loop to add a number to a ListBox. Thread 1 (th1) uses ListBox1 (left one), and thread 2 uses the other one. So if I launch the application and click over start both threads start to works sending numbers to its correspondent listbox. When finished I could try to click again and again, and the result would be different each time:



This is the code for the button START which will create and launch both Threads. I have used for this parametrized Threads because I need it to indicate over with listBox must the thread works



This is the code for the job assigned to the threads.


 


One important thing is that we cannot access the control directly because we are working with different threads, if I try to add the item to the list box in a different thread I would obtain a exception, so I need to create a delegate SetControlValueCallBack "pointing" to a method SetControlValue, to identify if this call came from a thread different from the thread in which was created the control. This is accomplished using the InvokeRequired.


In this case the method creates a new delegate type object, passing also the arguments received. This causes to call again the method, but this times using the same Thread, which causes to entry in the code that adds the value to the listbox without having an exception. 




No hay comentarios: