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 ?

1 Answer 1

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); }); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Ah I understand the continuation now. That accomplishes what I need. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.