Книга: C# 2008 Programmer
Passing Parameters to Threads
Passing Parameters to Threads
In the past few examples, you've seen how to create a thread using the ThreadStart
delegate to point to a method. So far, though, the method that you have been pointing to does not have any parameters:
static void DoSomething() {
...
...
}
What if the function you want to invoke as a thread has a parameter? In that case, you have two choices:
? Wrap the function inside a class, and pass in the parameter via a property.
? Use the ParameterizedThreadStart
delegate instead of the ThreadStart
delegate.
Using the same example, the first choice is to wrap the DoSomething() method as a class and then expose a property to take in the parameter value:
class Program {
static void Main(string[] args) {
SomeClass sc = new SomeClass();
sc.msg = "useful";
Thread t = new Thread(new ThreadStart(sc.DoSomething));
t.Start();
}
}
class SomeClass {
public string msg { get; set; }
public void DoSomething() {
try {
while (true) {
Console.WriteLine("Doing something...{0}", msg);
}
} catch (ThreadAbortException ex) {
Console.WriteLine(ex.Message);
} finally {
//---clean up your resources here---
}
}
}
In this example, you create a thread for the DoSomething()
method by creating a new instance of the SomeClass
class and then passing in the value through the msg property.
For the second choice, you use the ParameterizedThreadStart
delegate instead of the ThreadStart
delegate. The ParameterizedThreadStart
delegate takes a parameter of type object, so if the function that you want to invoke as a thread has a parameter, that parameter must be of type object
.
To see how to use the ParameterizedThreadStart
delegate, modify the DoSomething()
function by adding a parameter:
static void DoSomething(object msg) {
try {
while (true) {
Console.WriteLine("Doing something...{0}", msg);
}
} catch (ThreadAbortException ex) {
Console.WriteLine(ex.Message);
} finally {
//---clean up your resources here---
}
}
To invoke DoSomething()
as a thread and pass it a parameter, you use the ParameterizedThreadStart
delegate as follows:
static void Main(string[] args) {
Thread t = new Thread(new ParameterizedThreadStart(DoSomething));
t.Start("useful");
Console.WriteLine("Continuing with the execution...");
...
The argument to pass to the function is passed in the Start()
method.
- 10.2. THREADS
- 4 A few ways to use threads
- Printing Out the Parameters
- Positional Parameters
- 8.2.2. Module Parameters
- 4.1.2 Passing Arrays to Functions
- 4.1.3 Passing Variables by Reference to Functions
- 9.9.9 Calculating the Timing Parameters
- 4.1. THREADS
- 2.4.2. Parameter Passing
- 4.1.1. Introduction to Threads
- 4.1.3. Design Issues for Threads Packages