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.
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.
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