Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return data from a Threading Task

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 ?

like image 724
Web Avatar asked Mar 21 '11 16:03

Web


1 Answers

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);
       });
}
like image 94
Reed Copsey Avatar answered Oct 05 '22 08:10

Reed Copsey