How to pass parameters to ThreadStart method in Thread?
The simplest is just
string filename = ...
Thread thread = new Thread(() => download(filename));
thread.Start();
The advantage(s) of this (over ParameterizedThreadStart
) is that you can pass multiple parameters, and you get compile-time checking without needing to cast from object
all the time.
ThreadStart with parameters
Yep :
Thread t = new Thread (new ParameterizedThreadStart(myMethod));
t.Start (myParameterObject);
How to pass parameters to a thread in C#?
The problem with that code is that ParameterizedThreadStart
is a delegate type, which means it is tied to a specific method signature -- in particular, that signature is void method(object)
. Your method Thread2
does not match that signature, hence the compiler error.
So how to solve it? It depends really.
ParameterizedThreadStart
has that signature because it's the most generic approach ever. The idea behind it is that you can pass an object of some custom type that contains all the state your function needs, like this:
class Params
{
public int Start { get; set; }
public int End { get; set; }
public int[] Array { get; set; }
}
var p = new Params { 0, 0, new int[0] };
var t = new Thread(thr2.Thread2);
t.Start(p);
public int Thread2(object param)
{
var p = (Params)param;
// and now get your arguments as p.Start etc.
}
While this works, it's unwieldy and forces you to abandon the most natural signature for Thread2
. But you can do better by interposing an anonymous function to do the unpacking of arguments:
int start = 0, end = 0;
var arr = new int[0];
var t = new Thread(() => thr2.Thread2(start, end, arr));
If you choose to do this you have to be mindful of the fact that due to the mechanism the compiler uses to pass the arguments to the thread method, changing their values after t
is defined but before it is started will make Thread2
see the changed values.
Pass Parameters through ParameterizedThreadStart
lazyberezovsky has the right answer. I want to note that technically you can pass an arbitrary number of arguments using lambda expression due to variable capture:
var thread = new Thread(
() => DoMethod(a, b, c));
thread.Start();
This is a handy way of calling methods that don't fit the ThreadStart
or ParameterizedThreadStart
delegate, but be careful that you can easily cause a data race if you change the arguments in the parent thread after passing them to the child thread's code.
Passing parameter inside thread start
You can try
int value = 123;
fail objfail = new fail();
var t = new Thread(() => objfail.DoWork(value));
t.Start();
passing parameters to a thread
You need ParametrizedThreadStart
to pass a parameter to a thread.
Thread t1 = new Thread(new ParametrizedThreadStart(func1);
t1.Start(obj1);
ThreadStart with Parameter method
Thread t = new Thread(new ParameterizedThreadStart(loop));
t.Start("Hello world");
private void loop(object obj)
{
string str = (string)obj;
for (int i = 0; i < 100000; i++)
{
// Don't do this: you can't change a control from another thread. Danger Will Robinson!
textBox1.Text = i + str;
}
}
Note that the loop
method must accept an object
parameter, so you'll have to upcast the object
to your type. If you don't want, you can use a closure and an anonymous method:
string str = "Hello world";
Thread t = new Thread(() => {
for (int i = 0; i < 100000; i++)
{
// Don't do this: you can't change a control from another thread. Danger Will Robinson!
textBox1.Text = i + str;
}
});
t.Start();
In this way the anonymous method will "close" around str
and it will be similar as if you had passed the parameter. Similar because there are differences/problems on closing variables. In reality I would write something similar to:
string str = "Hello world";
{
string str2 = str;
Thread t = new Thread(() => {
for (int i = 0; i < 100000; i++)
{
// Don't do this: you can't change a control from another thread. Danger Will Robinson!
textBox1.Text = i + str2;
}
});
t.Start();
}
so that no one else can "touch" str2
.
If you need I can find some answer on SO that explain this "problem"
Related Topics
C# SQL Server - Passing a List to a Stored Procedure
An Implementation of the Fast Fourier Transform (Fft) in C#
Has an Event Handler Already Been Added
Determine the Number of Lines Within a Text File
No Output to Console from a Wpf Application
How to Set a Program to Launch at Startup
What Is the Use of "Ref" for Reference-Type Variables in C#
Programmatically Determine a Duration of a Locked Workstation
How to Run an Exe File from My C# Code
C# Convert String from Utf-8 to Iso-8859-1 (Latin1) H
Best Way to Access a Control on Another Form in Windows Forms
"A Project with an Output Type of Class Library Cannot Be Started Directly"
What Is [Serializable] and When Should I Use It
Transparent Background Image for Form - Smooth Edge Shape for the Form
Tolist()-- Does It Create a New List
Formatting Doubles for Output in C#
How to Convert Struct System.Byte Byte[] to a System.Io.Stream Object in C#