【问题标题】:Exception from thread doesn't bubble up to main thread来自线程的异常不会冒泡到主线程
【发布时间】:2013-02-21 12:12:10
【问题描述】:

我在这里开始一个任务:

System.Threading.Tasks.Task.Factory.StartNew( () =>
    RefreshCache(crmClientInfo)).ContinueWith(
        previous => RefreshCacheExceptionHandling(previous.Exception),
        TaskContinuationOptions.OnlyOnFaulted
    );

...这是我的工人:

public void RefreshCache(CrmClientInfo _crmClientInfo)
{
    AsyncManager.OutstandingOperations.Increment();

    Timer timer = new Timer(10000);
    timer.Elapsed += delegate
    {
        throw new AggregateException("Timeout!");
    };
    timer.Start();

    OtherServices.RefreshCache(crmClientInfo);
    AsyncManager.OutstandingOperations.Decrement();
}

如果异常不在计时器定义中而是在其他地方发生,则异常会正确冒泡到RefreshCacheExceptionHandling()。但是如果它从定时器(AgregateException("Timeout!");) 触发,那么线程不会中断。 为什么?

【问题讨论】:

  • 可能是因为计时器在单独的线程上运行...
  • 异常不能这样工作。异常只能向上传播调用链。他们不会横着走。
  • 但是,如果确实需要,我认为可以将此异常传递给另一个线程。不是很简单,但可以做到。

标签: c# .net multithreading exception exception-handling


【解决方案1】:

System.Threading.Timer 类在 ThreadPool 上进行回调 线程并且根本不使用事件模型。

查看文档,这里:http://msdn.microsoft.com/en-us/library/zdzx8wx8.aspx

【讨论】:

  • @Igor System.Timers.Timer 只是 System.Threading.Timer 的包装器。如果您从未设置过SynchronizingObject,则在 ThreadPool 线程上调用回调。您应该阅读 MSDN 中的备注部分:msdn.microsoft.com/en-us/library/system.timers.timer.aspx 此外,animaonline 链接的页面明确指出“Timer(链接到 System.Timers.Timer)类派生自 Component,因此它可以与视觉设计师一起使用;它也引发事件,但它在 ThreadPool 线程上引发它们。”
猜你喜欢
  • 2023-01-14
  • 1970-01-01
  • 2011-03-25
  • 1970-01-01
  • 2013-02-17
  • 2023-04-10
  • 2013-03-13
  • 1970-01-01
  • 2016-07-22
相关资源
最近更新 更多