5

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 ?

Web
  • 1,735
  • 2
  • 22
  • 36

1 Answers1

5

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);
       });
}
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373