Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadStart return value?

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();
like image 284
bigtv Avatar asked Feb 19 '26 21:02

bigtv


2 Answers

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());
like image 55
Thomas Levesque Avatar answered Feb 21 '26 09:02

Thomas Levesque


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.

like image 29
Tim Lloyd Avatar answered Feb 21 '26 11:02

Tim Lloyd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!