Search code examples
c#.netasynchronoustask-parallel-library

Task.WaitAsync vs Task.Wait


I know that Task.Wait() block thread in which it is executed.

Do I understand correctly that Task.WaitAsync() does not do this?

I tried to find information about it but I didn't find anything


Solution

  • WaitAsync will return a new task that needs to be awaited in turn. It's not used to avoid await, it's used to allow cancelling a wait for another task.

    If you want you await for a task to complete without blocking you'll have to use await in an async method, or use ContinueWith with the continuation code:

    async Task MyMethodAsync(Task myTask)
    {
       ...
       await myTask;
       ...
    }
    

    This code can await forever and doesn't allow cancelling the wait. If you want to stop waiting after a while you can use Task.WaitAsync

    ...
    try
    {
        await myTask.WaitAsync(TimeSpan.FromMinute(1));
    }
    catch(TimeoutException)
    {
        //Handle the timeout
    }
    ...
    

    Or you may want to cancel awaiting that task if a parent call signals cancellation through a CancellationTokenSource

    async Task MyMethod(Task someTask,CancellationToken cancellationToken=default)
    {
       ....
       await someTask.WaitAsync(cancellationToken);
       ...
    }