【发布时间】:2020-11-04 12:24:08
【问题描述】:
我遇到的问题是异常(标记如下)在抛出到围绕Task.WhenAll 的catch 语句时没有被捕获。我不确定为什么这个异常会膨胀到调用堆栈。
我阅读了以下article,其中声明了一个包装等待的任务的 try/catch。WhenAll 将捕获抛出的第一个异常,但对我来说似乎并非如此......
我在下面有以下代码 sn-p(您可以复制并粘贴它并点击“运行”)以重现(.netcoreapp2.1)。
using System;
using System.Threading.Tasks;
using System.Threading;
namespace TestProgram
{
class Program
{
public static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
private static async Task MainAsync(string[] args)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
var thread = new Thread(() => CancelToken(tokenSource));
thread.IsBackground = true;
thread.Start();
var ourTask = SpinUntilCancelled(token);
try
{
await Task.WhenAll(ourTask);
}
catch (Exception ex) // NOT CATCHING AND PRINTING!
{ Console.WriteLine($"{ex}"); }
}
private static void CancelToken(CancellationTokenSource obj)
{
Thread.Sleep(5000);
obj.Cancel();
obj.Dispose();
return;
}
private static Task SpinUntilCancelled(CancellationToken cancellation)
{
int i = 0;
while (true)
{
try
{
if (cancellation.IsCancellationRequested)
throw new ApplicationException("Token cancelled");
Thread.Sleep(1000);
Console.WriteLine($"Text {++i}");
}
catch
{
Console.WriteLine("Cancelled!");
cancellation.ThrowIfCancellationRequested();
}
}
}
}
}
如你所见,我的断点没有被命中。
【问题讨论】:
-
您的示例中没有异步代码,并且代码从不到达
.WhenAll或try/cathc块内...你错过了await Task.Delay()某处?总体问题看起来只是错字...... -
@AlexeiLevenkov 当它到达 SpinUntilCancelled 并在单独的线程调用 TokenSource 上的 Cancel 之前打印 Text1、Text2、Text3... 时,这怎么可能
-
不友好或不友好的评论:@TeeZadAwk 您是否尝试单步执行代码?你责备
try { await Task.WhenAll(ourTask); } ...代码在它甚至没有被调用... 时不起作用 -
@AlexeiLevenkov:你说得对,对不起......该方法不需要 return 语句,因为它永远无法完成,因为
while (true)。编译器甚至不会抱怨它。 -
@AlexeiLevenkov 你是对的!
标签: c# exception async-await try-catch task