Published articles on other web sites*

Published articles on other web sites*

Pass Argument to Threads in .NET

In this post, we will see how to use the .NET ParameterizedThreadStart delegate to pass arguments to Threads.
When you create a managed thread, in the Thread class constructor, you use either the ThreadStart or the ParameterizedThreadStart delegate to represent the method that executes on the thread. As given in the documentation, there are four thread constructors, as shown below:
image
There are two delegate types used in these constructors, whose definition are as follows:

threaddelegatetypes
In order to pass arguments to threads in .NET, you need to use the ParameterizedThreadStart delegate (introduced in .NET 2.0), which is an overloaded version of the Thread class constructor. The other delegate, i.e. the ThreadStart delegate takes no parameters and both these delegates are within the System.Threading namespace and return void.
The ParameterizedThreadStart delegate takes a single object as an argument. So this allows you to pass data to either a static or an instance method, to be executed.
Let us see an example:
using System;
using System.Threading;

namespace ThreadArguments
{
class Program
{
static void Main(string[] args)
{
// explicitly invoking ParameterizedThreadStart
// for illustration
Thread thread =
new Thread(new ParameterizedThreadStart(WelcomeMsg));
thread.IsBackground = true;
// Execute the thread and pass an argument
thread.Start('Hello from Main Thread');
Console.ReadLine();
}

static void WelcomeMsg(object str)
{
// cast to avoid runtime cast exceptions
String welcome = (String)str;
System.Console.WriteLine(welcome);
}
}
}
Note: Since the parameter passed in to the ParameterizedThreadStart is an object instance, you must cast it to the expected type in order to use it, else you may encounter runtime cast exceptions.
If you observe, we have explicitly used the new ParameterizedThreadStart(WelcomeMsg). However that’s not really needed. You can also use
Thread thread = new Thread(WelcomeMsg);
The C# compiler notices the signature of the method, and selects the Thread constructor that takes a ParameterizedThreadStart delegate.
OUTPUT
image
"

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...