Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a value from Thread

I see the class Thread has 4 constructors:

public Thread(ParameterizedThreadStart start);
public Thread(ThreadStart start);
public Thread(ParameterizedThreadStart start, int maxStackSize);
public Thread(ThreadStart start, int maxStackSize);

ParameterizedThreadStart and ThreadStart are delegate like this:

public delegate void ThreadStart();
public delegate void ParameterizedThreadStart(object obj);

What if I want to create thread start function that return int, for example? I see that the constructor is good only if i want return void.

like image 447
dani1999 Avatar asked Feb 21 '26 20:02

dani1999


1 Answers

You can use the Task Parallel Library which allows you to have a return value. If you actually want a new thread to be allocated, you can use the right overload of Task.Factory.StartNew:

public int DoSomething() { return 42; }
public async Task FooAsync()
{
    int value = await Task.Factory.StartNew(
                        () => DoSomething(), TaskCreationOptions.LongRunning);
}

If you don't actually need the new thread allocation, and can use a thread-pool thread, then using Task.Run is simpler and better:

public async Task FooAsync()
{
    int value = await Task.Run(() => DoSomething());
}

Edit:

If for some odd reason you really want to use the Thread class, you can do this by closing over a variable and passing it to a delegate pass to Thread.Start and rely on the side-effect created once the thread starts running:

var x = 5;
var thread = new Thread(() => 
{
    var x = DoSomething();
});

thread.Start();
thread.Join(); // This will synchronously block the thread.
Console.WriteLine(x);

Though I would definitely try to avoid this if you can use the TPL.

like image 89
Yuval Itzchakov Avatar answered Feb 24 '26 08:02

Yuval Itzchakov