第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

在Task中捕獲異常的最佳方法是什么?

在Task中捕獲異常的最佳方法是什么?

人到中年有點(diǎn)甜 2019-10-17 14:26:00
使用System.Threading.Tasks.Task<TResult>,我必須管理可能引發(fā)的異常。我正在尋找做到這一點(diǎn)的最佳方法。到目前為止,我已經(jīng)創(chuàng)建了一個(gè)基類,該基類在調(diào)用時(shí)管理所有未捕獲的異常。.ContinueWith(...)我想知道是否有更好的方法可以做到這一點(diǎn)。甚至是這樣做的好方法。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             */        });            }}
查看完整描述

2 回答

?
POPMUISE

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();


查看完整回答
反對(duì) 回復(fù) 2019-10-17
?
慕慕森

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)用程序的邏輯。


查看完整回答
反對(duì) 回復(fù) 2019-10-17
  • 2 回答
  • 0 關(guān)注
  • 1128 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)