C# Sending and Receiving Data From a Thread

C# Code Snippets Sending and Receiving Data From a Thread
Share:

About

In this code snippet, we will see how to pass/get data to/from a thread in C#.

To pass data into the thread we will simply pass it as an input parameter to the method that is being started as a new thread.

To get the data from the thread a delegate callback method will be used. First, we will make a regular method that takes in an input parameter. Then we will make a delegate and make it point to this method. Finally, the delegate will be passed as an input parameter to the method that is being started as a new thread. When the child thread is done executing it will call the callback method that is located in the main thread and pass it the result as an input parameter. This is how we will be able to get the result from the child thread back into the main one.

See this post if you want to know how to exchange data with a thread by using an object. It is very similar to what we are doing here.

Let’s have a look at the code below to see how to pass/get data to/from a thread.

Code:

Resulting output:

Share:

Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger