I am re factoring some legacy code, and I have updated the Task.Execute method used in the ThreadStart statement below to be used in another context. However now it causes a compile error saying Task.Execute has the wrong return type.
Why is this and how do I work around it so I can keep my return value but also the ThreadStart?
ThreadStart start = new ThreadStart(Task.Execute);
Thread asyncThread = new Thread(start);
asyncThread.IsBackground = true;
asyncThread.Start();
The return type of ThreadStart is void, so you must pass a method that returns void. If Task.Execute is non-void, you can use a lambda expression:
ThreadStart start = new ThreadStart(() => Task.Execute());
You need to write a wrapper for your Execute method which does not return a value, as ThreadStart delegate expects a method with a void return type:
public static class Task
{
public static int Execute()
{
//blah blah blah
return 1;
}
public static void ExecuteWrapper()
{
Execute();
}
}
Then:
ThreadStart start = new ThreadStart(Task.ExecuteWrapper);
Thread asyncThread = new Thread(start);
asyncThread.IsBackground = true;
asyncThread.Start();
Can the return value be safely ignored though? This often points to a design issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With