使用异步方法等待Task.Run不会在正确的线程上引发异常 [英] Awaiting Task.Run with async method does not throw exception on correct thread
问题描述
当运行下面的测试方法时,我发现即使我等待引发异常的任务,测试仍会通过.此外,将弹出一个单独的窗口,提示"QTAgent.exe已停止工作".这表明异常不会传播到运行测试的线程,而是杀死了一个单独的线程.
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?
请注意,如果我更改了它,以便如果func不是异步的,则异常会按预期在测试线程中引发.
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);
}
推荐答案
简单的调整:
[TestMethod]
public async Task TestWeirdTaskBehavior()
{
Func<Task> func = async () =>
{
await Task.Delay(0);
throw new InvalidOperationException();
};
await Task.Run(func);
}
您的 Action
本质上是一个 async void
.如果要等待它或将其包装在另一个 Task
中,则需要编译器为您吐出 Task
.在您的原始代码段中,外部任务( Task.Run(...)
)一旦内部任务达到第一个 await
,即 ,就会完成>引发异常.
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.
这篇关于使用异步方法等待Task.Run不会在正确的线程上引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!