Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

.net - How to handle all unhandled exceptions when using Task Parallel Library?

I'm using the TPL (Task Parallel Library) in .NET 4.0. I want to centralize the handling logic of all unhandled exceptions by using the Thread.GetDomain().UnhandledException event. However, in my application, the event is never fired for threads started with TPL code, e.g. Task.Factory.StartNew(...). The event is indeed fired if I use something like new Thread(threadStart).Start().

This MSDN article suggests to use Task.Wait() to catch the AggregateException when working with TPL, but that is not what I want because this mechanism is not "centralized" enough.

Does anyone experience same problem at all or is it just me? Do you have any solution for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think TaskScheduler.UnobservedTaskException Event is what you want:

Occurs when a faulted Task's unobserved exception is about to trigger exception escalation policy, which, by default, would terminate the process.

So, this event is similar to DomainUnhandledException that you mentioned in your question but occurs only for tasks.

BTW note, that unobserved-exceptions policy (yeah, this is not an unobserved exceptions, MS guys invented new word ... again), changed from .NET 4.0 to .NET 4.5. In .NET 4.0 unobserved exception leads to process termination but in .NET 4.5 - don't. This is all because new async stuff that we'll have in C# 5 and VB 11.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...