在ContinueWith new System.Threading.Timer中引发异常



我有以下示例代码:

public static void Main() 
{
    var t = Task.Factory.StartNew(() => 
    {
        string s = File.ReadAllText(@"C:Test.zip");
        return s;
    });
    var c = t.ContinueWith((_) => 
    {
       _myTimer = new Timer(TestItem, null, 2500, 2500);
    });
    Console.ReadKey();
}
private static void TestItem(object data)
{
    try 
    {
        throw new Exception("My Test Error");
    } 
    catch (Exception) 
    {
        _myTimer.Change(Timeout.Infinite, Timeout.Infinite);
        throw;
    }
}

如何捕获从TestItem抛出的错误。有没有一种方法可以监视TestItem的错误?

目前在visual studio中,它给了我一个未处理的异常,我该如何处理它?

我想知道是否有人能帮助我或为我指明正确的方向。

您无法捕获它,TestItem()在任务完成后很长一段时间才在线程池线程上运行。AppDomain.UnhandledException是最好的。如果不希望程序终止,则必须捕获并处理TestItem()内的异常。

Delay()将是一个明智的选择。

我认为您需要的是完全不同的东西:

static async Task TestItem()
{
    while (true) {
     try 
     {
         await Task.Delay(2500);
         throw new Exception("My Test Error");
     } 
     catch (Exception) 
     {
        //TODO for you: handle
     }
    }
}

只需在Main:中调用该方法

TestItem(); //no await

你的计时器可以触发多次,这是一个错误。所有这些都随着现代API的使用而消失。抛弃现有的方法。

var c = t.ContinueWith(tk => 
{
    _myTimer = new Timer(TestItem, null, 2500, 2500);
    //you can check the type of exception, etc
    //if(tk.Exception is AggregateException) //etc
    var message = tk.Exception.Message;
}, TaskContinuationOptions.OnlyOnFaulted);

最新更新