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

与世无争的帅哥 提交于 2021-02-05 07:21:25

问题


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);
 }

回答1:


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.



来源:https://stackoverflow.com/questions/34167849/awaiting-task-run-with-async-method-does-not-throw-exception-on-correct-thread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!