问题
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