Passing Data to Threads and Retrieving Data from Threads

When you do calls to components, which may need some time to respond, it is very essentially to put this calls in a separate thread. Otherwise you risk your application to bug for a while.

When you work with many threads sometimes you will need to pass data between them. Although .NET Framework provides an easy way to achieve this goal, I will show you another solution of this problem, which is more secure.

Don’t forget to include using System.Threading; at the beginning. Well, everything is O.K. But now if you want to pass a parameter to this function? There is one standard way to do this, but I am going to show you another, a better one. When you create a new Thread object you may specify two delegates: ThreadStart or ParameterizedThreadStart. As you suppose, using the second delegate can help us.

Using ParameterizedThreadStart you can specify a void function, which accepts only one argument of type object. Then when you start the thread, you pass an object parameter. This technique is not very safe, because you can pass any object to the thread. A far better way is to create an auxiliary class, which includes a both the thread procedure and the data fields.

This variant is safer and more convenient. Now, is you want your thread to do some work and then to return the results of its work, you can use a callback function. Here is simple example that illustrates this issue.

Well, that the whole technique! Its easy to use and modify.