ThreadStart with parameters
Yep :
Thread t = new Thread (new ParameterizedThreadStart(myMethod));
t.Start (myParameterObject);
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 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"
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);
thread with multiple parameters
Try using a lambda expression to capture the arguments.
Thread standardTCPServerThread =
new Thread(
unused => startSocketServerAsThread(initializeMemberBalance, arg, 60000)
);
How to create a thread with multiple parameters?
You can make it super easy by just doing this:
Thread wms = new Thread(() => appUpdater("WMS", "StuMenu"));
wms.Start();
Alternatively, use a Task
- tasks are more modern and you'll find built in language support for doing clever things with them. Don't learn threads, learn tasks.
Task t = Task.Run(() => appUpdater("WMS", "StuMenu"));
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.
Store a thread with multiple parameters - WPF
You can encapsulate the parameters in a class, but you can encapsulate also your logic in the class:
public class FooProcessor
{
private readonly Color _color1;
private readonly Color _color2;
public FooProcessor(Color color1, Color color2)
{
_color1 = color1;
_color2 = color2;
}
public Task ProcessAsync()
{
return Task.Run((Action) Process);
}
private void Process()
{
//add your logic here
}
}
OT: if you don't have specific reason to use Thread
instead of Task
, use Task
. Some older tutorials use Threads, because Task didn't exist at that time.
Error on passing parameterised method in C# thread
Try this...
void Main()
{
ClassA obj = new ClassA();
Thread thread = new Thread(() => obj.MethodA("Param1", 2));
thread.Start();
thread.Join();
}
class ClassA
{
public void MethodA(string par1, int par2)
{
Console.WriteLine("Parameter " + par1 + " is passed with value " + par2);
}
}
The Issue...
As others have already stated, you have too many parameters...
Other than that you're also not waiting for the thread to complete it's operation.
What you see above is called a lambda expression, basically an anonymous function, and you could compose it in a number of ways, the above is just one example.
Here's another...
void Main()
{
ClassA obj = new ClassA();
Thread thread = new Thread(()=>
{
Console.WriteLine ("About to execute MethodA");
obj.MethodA("test", 2);
Console.WriteLine ("Executed Method A");
});
thread.Start();
thread.Join();
}
class ClassA
{
public void MethodA(string par1, int par2)
{
Console.WriteLine("Parameter " + par1 + " is passed with value " + par2);
}
}
If you need further help, let me know
Related Topics
How to Find If a Native Dll File Is Compiled as X64 or X86
Are Static Class Instances Unique to a Request or a Server in ASP.NET
How to Get This ASP.NET MVC Selectlist to Work
How to Convert a Decimal to a Double in C#
Differencebetween "X Is Null" and "X == Null"
How to Trap Ctrl+C (Sigint) in a C# Console App
Get Controller and Action Name from Within Controller
Convert Any Object to a Byte[]
Which Version of C# am I Using
What Is the Minimum Client Footprint Required to Connect C# to an Oracle Database
Localization of Displaynameattribute
Using a Self-Signed Certificate with .Net's Httpwebrequest/Response
Multiple Actions Were Found That Match the Request in Web API
Bring a Window to the Front in Wpf
Token Based Authentication in Web API Without Any User Interface