Scott Kausler
Scott Kausler

Reputation: 161

Awaiting Task.Run with async method does not throw exception on correct thread

When running the test method below, I found that even though I await a task that throws an exception, the test passes. Furthermore, a separate window pops up saying "QTAgent.exe has stopped working". This indicates that the exception is not propagated to the thread running the test and instead kills a separate thread.

I would like to know why this happens. Also, since this doesn't appear to work as intended, how should I run an async method on a thread pool thread?

Note that if I change it so that if func is not async, the exception is thrown in the test thread as expected.

 [TestMethod]
 public async Task TestWeirdTaskBehavior()
 {
      Action func = async () =>
      {
           await Task.Delay(0);
           throw new InvalidOperationException();
      };
      await Task.Run(func);
 }

Upvotes: 2

Views: 695

Answers (1)

Kirill Shlenskiy
Kirill Shlenskiy

Reputation: 9587

Simple tweak:

[TestMethod]
public async Task TestWeirdTaskBehavior()
{
    Func<Task> func = async () =>
    {
        await Task.Delay(0);
        throw new InvalidOperationException();
    };
    await Task.Run(func);
}

Your Action is essentially an async void. You need the compiler to spit out a Task for you if you want to await it or wrap it in another Task. In your original snippet the outer task (Task.Run(...)) completes as soon as the inner task hits the first await, before the exception is thrown.

Upvotes: 8

Related Questions