使用
我在想有没有更好的办法。或者即使这是一个好方法。
public class BaseClass
{
protected void ExecuteIfTaskIsNotFaulted<T>(Task<T> e, Action action)
{
if (!e.IsFaulted) { action(); }
else
{
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
{
/* I display a window explaining the error in the GUI
* and I log the error.
*/
this.Handle.Error(e.Exception);
}));
}
}
}
public class ChildClass : BaseClass
{
public void DoItInAThread()
{
var context = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew<StateObject>(() => this.Action())
.ContinueWith(e => this.ContinuedAction(e), context);
}
private void ContinuedAction(Task<StateObject> e)
{
this.ExecuteIfTaskIsNotFaulted(e, () =>
{
/* The action to execute
* I do stuff with e.Result
*/
});
}
}
有两种方法可以做到这一点,这取决于您所使用的语言版本。
您可以使用
在语言中引入了
因此,您可以简单地使用
try
{
// Start the task.
var task = Task.Factory.StartNew<StateObject>(() => { /* action */ });
// Await the task.
await task;
}
catch (Exception e)
{
// Perform cleanup here.
}
注意,封装上面的方法必须应用
您可以使用从
// Get the task.
var task = Task.Factory.StartNew<StateObject>(() => { /* action */ });
// For error handling.
task.ContinueWith(t => { /* error handling */ }, context,
TaskContinuationOptions.OnlyOnFaulted);
当然,您可以对同一先行项的
// Get the task.
var task = new Task<StateObject>(() => { /* action */ });
// For error handling.
task.ContinueWith(t => { /* error handling */ }, context,
TaskContinuationOptions.OnlyOnFaulted);
// If it succeeded.
task.ContinueWith(t => { /* on success */ }, context,
TaskContinuationOptions.OnlyOnRanToCompletion);
// Run task.
task.Start();
您可以创建一些自定义任务工厂,它将生成嵌入异常处理处理的任务。像这样的东西:
using System;
using System.Threading.Tasks;
class FaFTaskFactory
{
public static Task StartNew(Action action)
{
return Task.Factory.StartNew(action).ContinueWith(
c =>
{
AggregateException exception = c.Exception;
// Your Exception Handling Code
},
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously
).ContinueWith(
c =>
{
// Your task accomplishing Code
},
TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously
);
}
public static Task StartNew(Action action, Action<Task> exception_handler, Action<Task> completion_handler)
{
return Task.Factory.StartNew(action).ContinueWith(
exception_handler,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously
).ContinueWith(
completion_handler,
TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously
);
}
};
您可以忘记在客户端代码中对从该工厂产生的任务进行异常处理。同时,您仍然可以等待这些任务的完成,或者以“火了就忘了”的方式使用它们:
var task1 = FaFTaskFactory.StartNew( () => { throw new NullReferenceException(); } );
var task2 = FaFTaskFactory.StartNew( () => { throw new NullReferenceException(); },
c => { Console.WriteLine("Exception!"); },
c => { Console.WriteLine("Success!" ); } );
task1.Wait(); // You can omit this
task2.Wait(); // You can omit this
但是老实说,我真的不确定为什么你想要完成处理代码。在任何情况下,这个决定取决于您的应用程序的逻辑。