2 回答

TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個(gè)贊
有兩種方法可以執(zhí)行此操作,具體取決于您所使用的語(yǔ)言版本。
C#5.0以上
您可以使用async和await關(guān)鍵字為您簡(jiǎn)化很多操作。
async并且await被引入該語(yǔ)言以簡(jiǎn)化使用Task Parallel Library的工作,從而避免了您必須使用ContinueWith并允許您以自上而下的方式繼續(xù)編程。
因此,您可以簡(jiǎn)單地使用try/catch塊來(lái)捕獲異常,如下所示:
try
{
// Start the task.
var task = Task.Factory.StartNew<StateObject>(() => { /* action */ });
// Await the task.
await task;
}
catch (Exception e)
{
// Perform cleanup here.
}
請(qǐng)注意,封裝上述內(nèi)容的方法必須使用已a(bǔ)sync應(yīng)用關(guān)鍵字,這樣您才可以使用await。
C#4.0及以下
您可以使用從枚舉中獲取值的ContinueWith重載來(lái)處理異常,如下所示:TaskContinuationOptions
// Get the task.
var task = Task.Factory.StartNew<StateObject>(() => { /* action */ });
// For error handling.
task.ContinueWith(t => { /* error handling */ }, context,
TaskContinuationOptions.OnlyOnFaulted);
在OnlyOnFaulted該成員TaskContinuationOptions枚舉指示應(yīng)繼續(xù)只當(dāng)先行任務(wù)拋出異常執(zhí)行。
當(dāng)然,您可以有多個(gè)調(diào)用來(lái)ContinueWith取消同一先決條件,從而處理非例外情況:
// 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();

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超17個(gè)贊
您可以創(chuàng)建一些自定義的Task工廠,該工廠將生成嵌入了異常處理過(guò)程的Task。像這樣:
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
);
}
};
您可以在客戶端代碼中忘記從該工廠生成的任務(wù)的異常處理。同時(shí),您仍然可以等待此類任務(wù)的完成或以“一勞永逸”的方式使用它們:
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
但是,老實(shí)說(shuō),我不太確定為什么要使用完成處理代碼。無(wú)論如何,此決定取決于您的應(yīng)用程序的邏輯。
- 2 回答
- 0 關(guān)注
- 1128 瀏覽
添加回答
舉報(bào)