C#中的例外有多贵?只要堆叠不深,它们似乎并不是非常昂贵; 但我读过相互矛盾的报道.
有没有被反驳的确定性报告?
我发现自己经常编写这样的代码:
try
{
cancellationTokenSource.Cancel();
await task.ConfigureAwait(false); // this is the task that was cancelled
}
catch(OperationCanceledException)
{
// Cancellation expected and requested
}
Run Code Online (Sandbox Code Playgroud)
鉴于我请求取消,这是预料之中的,而且我真的希望忽略该异常。这似乎是一个常见的案例。
有没有更简洁的方法来做到这一点?我是否错过了有关取消的信息?看来应该有什么task.CancellationExpected()方法什么的。
如何在请求取消之前暂停执行?
var cts = new CancellationTokenSource();
Task.Run(() =>
{
// Wait for the Cancel...
Console.WriteLine("Canceled!");
});
Console.ReadKey();
cts.Cancel();
Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)