C 多執行緒中的異常處理

2021-09-23 10:23:10 字數 2519 閱讀 7934

使用thread建立的子執行緒,需要在委託中捕捉,無法在上下文執行緒中捕捉

static void main(string args)

static void dowork()

catch (exception ex)

}

1.仍然可以在委託中捕獲異常

2.可以捕獲task.wait() 或者 task.result 的 aggregateexception 異常

try

catch (aggregateexception ex)

"); foreach (exception item in ex.innerexceptions)

, ");}}

aggregateexception 是並行任務中捕獲的一組異常

static void main(string args)

"); return true;

});},taskcontinuationoptions.onlyonfaulted);

faultedtask.wait();

}

前驅任務:使用run書寫的第乙個任務就是前驅任務

延續任務:在乙個任務後使用continuewith新增的任務就是延續任務,延續一般是乙個全新的工作執行緒

taskcontinuationoptions:指定延續任務時的可配置項,預設情況下前驅任務完成後,立即執行延續任務,onlyonfaulted表示只有前驅任務失敗(出異常的時候)才會執行這乙個延續任務

task.exception也是乙個aggregateexception 異常

注意:1.當指定的taskcontinuationoptions與前驅任務執行結果不一致時,強制呼叫延續任務wait()會引發taskcanceledexception異常

static void main(string args)

); task faultedtask = task.continuewith(antecedenttask =>

, taskcontinuationoptions.onlyonfaulted);

task.start();

trycatch (aggregateexception ex)

");foreach (exception item in ex.innerexceptions)

, ");}}

console.writeline($"前驅任務狀態");

console.writeline($"延續任務狀態");

}

ctrl+f5 輸出

補充:假如在前驅任務**現了異常,如onlyonfaulted所願,會執行faultedtask任務,並且在faultedtask.wait()中不會捕捉到前驅任務的異常,具體看下面一點

2.延續任務雖然在非同步任務中提供了類似if else 的continuewith但是在異常處理上還是有點侷限,看乙個例子

static void main(string args)

); task task2 = task1.continuewith(antecedenttask =>

);task task3 = task2.continuewith(antecedenttask =>

);try

catch (aggregateexception ex)

");foreach (exception item in ex.innerexceptions)

, ");}}

}

ctrl+f5 輸出

其實這樣也可以理解,task3.wait()只會收集task3所在工作執行緒上的異常,遺憾的是task.exception.innerexceptions是乙個唯讀集合,這樣一來,每個任務的異常只能在各自委託中處理了,事實上也應該如此,可以使用taskcontinuationoptions進行靈活控制

static void main(string args)

); cancellationtokensource.cancelafter(2000);

task task = task.run(() =>

},cancellationtokensource.token);

task.wait();

console.writeline($"任務的最終狀態是:");

}

ctrl+f5 輸出

正常取消的任務最終狀態是 rantocompletion ,這裡要注意的是,cancelafter()是在這個方法呼叫的那一刻開始計時的(並非以run開始計時,好吧,很好理解,我卻疑惑了半天)

C 中多執行緒異常的處理

在建立多執行緒的時候,啟動多執行緒時候使用try catch捕獲不多異常。需要在主程式的地方加上異常處理方法。處理未捕獲的異常 處理ui執行緒異常 處理非ui執行緒異常 region 處理未捕獲異常的掛鉤函式 n異常訊息 n異常位置 n error.gettype name,error.messag...

C std thread 多執行緒中的異常處理

環境 vs2019 包含標頭檔案 include include include 執行緒函式採用trycatch 機制 如果需要在主線程檢測子執行緒的異常時,採用全域性變數的方式獲取 std exception ptr ptr void f0 str.at 2 越界訪問 throw std exce...

多執行緒的異常處理

1.coding utf 8 defget multithreading res executor,fun name,arg list i 1 0 return list executor.map fun name,arg list deftask func i try if i a i i 0 r...