Reputation: 743
If I have a
public void Method(int m)
{
...
}
how can I create a thread to this method?
Thread t = new Thread((Method));
t.Start(m);
is not working.
Upvotes: 18
Views: 35794
Reputation: 14391
The method you are calling requires a parameter. Because it has one parameter and a return type of void you can use the following
ThreadPool.QueueUserWorkItem(o => Method(m));
You do not need to change the int to an object in the method signature using this method.
There are advantages to using the ThreadPool over starting your own Thread manually. Thread vs ThreadPool
Upvotes: 14
Reputation: 6711
You can do this using a lambda expression. The C# compiler automatically creates the ThreadStart
delegate behind the scenes.
Thread t = new Thread(() => Method(m));
t.Start();
Note that if you change m
later in your code, the changes will propagate into the thread if it hasn't entered Method
yet. If this is a problem, you should make a copy of m
.
Upvotes: 29
Reputation: 4503
ThreadStart tsd = new ThreadStart(ThreadMethod);
Thread t = new Thread(tsd);
t.Start();
Thread methods needs to be a method with return type void and accepting no argument.
public void ThreadMethod() {.....}
There is another variant which is ParameterizedThreadStart
ParameterizedThreadStart ptsd = new ParameterizedThreadStart(ThreadParamMethod);
Thread t = new Thread(ptsd);
t.Start(yourIntegerValue);
ThreadParamMethod is a method which return type is void and accept one argument of type object. However you can pass just about any thing as object.
public void ThreadParamMethod(object arg) {.....}
Upvotes: 9
Reputation: 21713
Method needs to take an object not an int to be able to use the ParameterizedThreadStart delegate.
So change m to an object and cast it to an int first off.
Upvotes: 2
Reputation: 170
please try:
Thread t = new Thread(new ThreadStart(method));
t.Start();
Upvotes: -1