Mic*_*eth 44 .net c# multithreading threadpool
我有以下代码抛出异常:
ThreadPool.QueueUserWorkItem(state => action());
Run Code Online (Sandbox Code Playgroud)
当操作抛出异常时,我的程序崩溃了.处理这种情况的最佳做法是什么?
Pra*_*ter 70
您可以像这样添加try/catch:
ThreadPool.QueueUserWorkItem(state =>
{
try
{
action();
}
catch (Exception ex)
{
OnException(ex);
}
});
Run Code Online (Sandbox Code Playgroud)
Sam*_*ack 19
如果你使用的是.Net 4.0,那么调查Task类可能是值得的,因为它可以为你解决这个问题.
相当于原始代码,但使用Tasks,看起来像
Task.Factory.StartNew(state => action(), state);
Run Code Online (Sandbox Code Playgroud)
要处理异常,可以为StartNew返回的Task添加一个延续.它可能看起来像这样:
var task = Task.Factory.StartNew(state => action(), state);
task.ContinueWith(t =>
{
var exception = t.Exception.InnerException;
// handle the exception here
// (note that we access InnerException, because tasks always wrap
// exceptions in an AggregateException)
},
TaskContinuationOptions.OnlyOnFaulted);
Run Code Online (Sandbox Code Playgroud)