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

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".


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.


 Task task = Task.Run ( () => { Thread.Sleep ( 2000 ); } );

 task.GetAwaiter ().OnCompleted ( () => 
   {
     MessageBox.Show ( "the task completed in the main thread", "");
   } );

You can apply a task continuation.

Alternatively, Task implements IAsyncResult, so you can use the standard approaches for that interface (blocking, polling, or waiting on its WaitHandle).