2013-02-21 37 views
2

在这里,我开始一个任务:异常不能上升到主线程

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!");)触发,那么线程不会中断。 为什么?

+0

Proably因为计时器上一个单独的线程上运行... – animaonline 2013-02-21 12:14:40

+4

的异常不会这样的。异常只能传播呼叫链。他们不会横着。 – 2013-02-21 12:15:42

+0

但是,我认为如果真的需要,可以将这个异常传递给另一个线程。不是很简单,但可以完成。 – 2013-02-21 12:49:23

回答

1

的System.Threading.Timer类使得在一个线程池 线程回调并不会在所有使用的事件模型。

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

+0

这不是System.Threading.Timer。它的System.Timers.Timer – Igor 2013-02-21 12:22:25

+1

@Igor System.Timers.Timer只是一个System.Threading.Timer的包装。如果您从未设置“SynchronizingObject”,则在ThreadPool线程上调用该回调。您应该阅读MSDN中的备注部分:http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx此外,由animaonline链接的页面明确指出“定时器(链接到系统。 Timers.Timer)类派生自Component,所以它可以与视觉设计师一起使用;它也会引发事件,但它会在一个ThreadPool线程上引发它们。“ – cremor 2013-02-21 12:50:45

相关问题