I am currently trying to use a .net Task to run a long method. I need to be able to return data from the task. I would like to call this method multiple times each time running it in a new task. However, returning data using the Task.Result property makes each task wait until complete.
For example currently if do something like this :
public void RunTask()
{
var task = Task.Factory.StartNew(() =>
{
return LongMethod()
});
Console.WriteLine(task.Result);
}
and call it multiple times, each time taking a different amount of time, it is waits for each Task to complete before executing the next.
Is it possible to call my RunTask method multiple times, each time returning a result without having to wait for each task to complete in order ?
Yes. When you call task.Result
on a Task<T>
, it will block until a result occurs.
If you want to make this completely asynchronous, you could either change your method to return the Task<T>
directly, and "block" at the caller's level, or use a continuation:
public void RunTask()
{
var task = Task.Factory.StartNew(() =>
{
return LongMethod()
});
// This task will run after the first has completed...
task.ContinueWith( t =>
{
Console.WriteLine(t.Result);
});
}
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