How to return data from a threading task

I'm currently trying to use a .net task to run a long method. I need to be able to return data from a task. I would like to call this method several times each time I run it in a new task. However, returning data using the Task.Result property causes each task to wait until completion.

For example, if you do something like this:

public void RunTask() { var task = Task.Factory.StartNew(() => { return LongMethod() }); Console.WriteLine(task.Result); } 

and name it several times, each time a different time is required, it waits for the completion of each task before completing the next.

Can I call my RunTask method several times, returning a result each time without waiting for each task to complete?

+4
source share
1 answer

Yes. When you call task.Result in Task<T> , it will block until the result occurs.

If you want to make it completely asynchronous, you can either change your method to return Task<T> directly, and “block” it at the caller level, or use the 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); }); } 
+5
source

Source: https://habr.com/ru/post/1344632/


All Articles