各位,请使用以下代码:
```
Task<bool> generateStageAsyncTask = null;
generateStageAsyncTask = Task.Factory.StartNew<bool>(() =>
{
return GenerateStage(ref workbook);
}, this.token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
// Run core asynchroniously.
bool bGenerationSuccess = false;
try
{
bGenerationSuccess = await generateStageAsyncTask;
}
catch (OperationCancelledException e)
{
// Script cancellation.
result.RunSucceeded = true;
result.ResultInfo = "Script processing cancelled at the users request.";
return result;
}
在方法GenerateStage
内部,我按以下方式测试并重新抛出OperationCancelledException
try
{
...
}
catch (Exception e)
{
if (e.GetType() == typeof(OperationCanceledException))
throw e;
else // <- Here it is saying that the thrown exception is unhandled.
{
// Do other stuff...
}
}
但是在上述指定的行中,它表明重新抛出的异常未经处理。我将第一个代码片段中的await
用适当的try/catch
包装起来,为什么这个try/catch
没有捕获重新抛出的异常呢?
catch(OperationCanceledException)
? - Peter Ritchieresult
是什么,它在哪里定义的,在哪里赋值的? - Peter RitchieCancelationTokenSource
取消操作,该操作来自于token
? - Peter Ritchiethrow e;
。 - MoonKnight