Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get notification that a System.Threading.Tasks.Task has completed

Tags:

c#

.net

.net-4.0

I am currently replacing some home baked task functionality with a new implementation using the new System.Threading.Tasks functionality found in .net 4.

I have a slight issue though, and although I can think of some solutions I would like some advice on which is generally the best way to do it, and if I am missing a trick somewhere.

What I need is for an arbitrary process to be able to start a Task but then carry on and not wait for the Task to finish. Not a problem, but when I then need to do something with the result of a task i'm not quite sure the best way of doing it.

All the examples I have seen use either Wait() on the task until it completes or references the Result parameter on the task. Both of these will block the thread which started the Task, which I don't want.

Some solutions I have thought of:

  1. Create a new thread and start the task on that, then use Wait() or .Result to block the new thread and sync the result back to the caller somehow, possibly with polling to the tasks IsCompleted parameter.

  2. Have a 'Notify Completed' task which I can start after completion of the task I want to run which then raises a static event or something.

  3. Pass a delegate into the input of the task and call that to notify that the task is finished.

I can think or pros and cons to all of them, but I especially don't like the idea of having to explicitly create a new thread to start the task on when the one of the aims of using the Task class in the first place is to abstract away from direct Thread usage.

Any thoughts about the best way? Am I missing something simple? Would a 'Completed' event be too much to ask for :)? (Sure there is a good reason why there isn't one!)

like image 958
Ben Williams Avatar asked Aug 11 '10 19:08

Ben Williams


People also ask

What is using system threading tasks in C#?

Tasks Namespace. Provides types that simplify the work of writing concurrent and asynchronous code. The main types are Task which represents an asynchronous operation that can be waited on and cancelled, and Task<TResult>, which is a task that can return a value.

What is the difference between threads and tasks?

A thread is one of the many possible workers which performs that task. In . NET 4.0 terms, a Task represents an asynchronous operation. Thread(s) are used to complete that operation by breaking the work up into chunks and assigning to separate threads.

Is task better than thread?

It is always advised to use tasks instead of thread as it is created on the thread pool which has already system created threads to improve the performance. The task can return a result. There is no direct mechanism to return the result from a thread. Task supports cancellation through the use of cancellation tokens.


2 Answers

I suspect you're looking for Task.ContinueWith (or Task<T>.ContinueWith). These basically say, "When you've finished this task, execute this action." However, there are various options you can specify to take more control over it.

MSDN goes into a lot more detail on this in "How to: Chain Multiple Tasks With Continuations" and "Continuation Tasks".

like image 120
Jon Skeet Avatar answered Sep 23 '22 03:09

Jon Skeet


In modern C#, one no longer needs to call ContinueWith() explicitly. An alternative to the original accepted answer would be to simply create an async method that awaits the Task in question, and does whatever it wants when the Task completes.

For example, suppose you want to raise an event called TaskCompleted when the Task completes. You would write a method like:

async Task RaiseEventWhenTaskCompleted(Task task) {     await task;     TaskCompleted?.Invoke(this, EventArgs.Empty); } 

To "register" the wait, just call the above method. Add exception handling as desired, either in the method above, or in some code that will eventually observe the Task returned by the above method.

like image 31
Peter Duniho Avatar answered Sep 20 '22 03:09

Peter Duniho