About
In this code snippet, we will see how to exchange thread data by using an object in C#.
This post is very similar to this post I already made about sending/receiving data to/from a thread. The only difference is that here an object will be used for the data.
To pass data into the thread we will create a class and make two properties one for the input data and one for the callback delegate. When an instance of the class is being created the input data and the callback delegate must be passed into the constructor. After the object has been created its doWork() method can be started as a new thread.
To get data out of the thread displayResult() will be called when doWork() is done executing. The result data will be passed as an input parameter to displayResult().
Note: In most cases, the best way to work with threads is by using the TPL(Task Parallel Library). Consider using it instead of working with threads directly like shown in this post.
Let’s have a look at the code below to see how to exchange thread data by using an object.
Code:
using System; using System.Threading; namespace ThreadDataExchangeByObject { //Define callback delegate. public delegate void doWorkCallback(int result); class Program { static void Main(string[] args) { //Make delgate that will call the displayWorkDone() method and pass it the value given the doWork() method from the MyClass class. doWorkCallback callback = new doWorkCallback(displayWorkDone); //Make an instance of MyClass. MyClass MC = new MyClass(5, callback); //Call doWork in new thread. Thread th = new Thread(MC.doWork); //Thread strat. th.Start(); Console.ReadLine(); } public static void displayWorkDone(int result) { Console.WriteLine("Result: " + result); } } class MyClass { int myParemeter; doWorkCallback callback; public MyClass(int parameter, doWorkCallback callbackIn) { //On class instantiation set the input parameter for the doWork method and //set the callback method that will be used to return back the data. myParemeter = parameter; callback = callbackIn; } public void doWork() { int result = 0; for (int i = 0; i < myParemeter; i++) { //Do some work.... Thread.Sleep(500); result += 10; } //Pass the result to the callback method. callback(result); } } }