There's a difference between:
- Call
PerformLongRunningWork
and it throws an exception.
- Call
PerformLongRunningWork
and it successfully executes, and gives you back a Task<string>
which contains an exception.
That is:
Task<string> task;
try
{
task = PerformLongRunningOperation();
}
catch (Exception e)
{
// PerformLongRunningOperation itself threw
}
bool containsException = task.IsFaulted;
try
{
string result = await task;
}
catch (Exception e)
{
// The Task<string> returned from PerformLongRunningWork contained an exception
}
If you throw an exception from an async Task
method, that exception is wrapped up inside the Task
which is returned.
Therefore, your example with a non-async
method which delegates to an async
local function will throw those ArgumentException
directly when it's called, and not return them wrapped up in the Task<string>
it returns.
If you rewrote the example to remove the local function and instead make PerformLongRunningWork
async
, then those ArgumentExceptions
would be wrapped up inside the Task<string>
returned.
Which one you want to do is a matter of debate.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…