Why is TaskAwaiter not awaitable?

Viewed 169

Context

I was playing with https://github.com/microsoft/vs-threading, and in particular its analyzers, and they have a rule that you should not await a task if it has was created in a different context.

In my program, i am using an extension method AutoHandleExceptionAsync which automates the exception handling of Tasks, and that method is supposed to simply be chained after the async method which returns the Task. Of course, AutoHandleExceptionAsync should either await the Task, or return the Task directly. Something like :

public static async Task AutoHandleExceptionAsync(this Task task)
{
    task.ContinueWith(
            HandleException,
            CancellationToken.None,
            TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.RunContinuationsAsynchronously,
            TaskScheduler.Default)
        .Forget();
    await Task;
}

VSThreading's analyzer complain that i should not await or return the Task since i didn't create it. Since this is an extension method, i feel like it could be considered a bug in the analyzer, but that's another topic.

In order to circumvent the warning, i thought of returning the awaiter for the Task directly. Then i noticed that TaskAwaiter, by default, can't be awaited.

Actual Question

I can make the awaiter awaitable with a simple extension method :

public static TaskAwaiter GetAwaiter(this TaskAwaiter awaiter) => awaiter;

I was worried it might create an infinite loop of sorts, but in a simple test it seemed ok. If it just works, i wonder why this wasn't implemented by default. Could there be some scenario where this breaks things ?

0 Answers
Related