我正在嘗試按照我的 MSDN 提供的示例在 C# 中實現(xiàn)任務(wù)取消。我有一個帶有圖形的 Windows 窗體應(yīng)用程序,顯示來自外部設(shè)備的數(shù)據(jù)和一個開始/停止按鈕。這或多或少是按鈕內(nèi)的代碼:if (drawGraph_task == null){ cts = new System.Threading.CancellationTokenSource(); token = cts.Token; drawGraph_task = new Task(() => { this.Invoke(new InvokeDelegate(this.myChart.Series[0].Points.Clear)); while (true) { // get x and y from device using external lib this.Invoke(new addPointXYDelegate(this.myChart.Series[0].Points.AddXY), new object[] { x, y }); this.Invoke(new InvokeDelegate(this.chart_pressure.Update)); // update graph if (token.IsCancellationRequested) { return; } } }, token); this.button_main_start.Text = "Stop"; drawGraph_task.Start(); }else{ cts.Cancel(); try { drawGraph_task.Wait(); } catch (AggregateException ae) { // do nothing } finally { cts.Dispose(); drawGraph_task.Dispose(); drawGraph_task = null; this.button_main_start.Text = "Restart"; }}為什么代碼仍然停留在 drawGraph_task.Wait() 調(diào)用中?我試圖在任務(wù)中使用 token.throwIfCancellationRequested() ,但有時我有同樣的效果,有時我的捕獲沒有捕獲異常。我究竟做錯了什么?為完整起見,x 和 y 的計算涉及:MathNet 插值庫調(diào)用內(nèi)部制作的庫進行特定于協(xié)議的通信以等待事件(它總是被啟動,所以這不是問題的根源)
為什么如果我嘗試使用 CancellationToken.Cancel() 停止任務(wù)
寶慕林4294392
2021-09-19 16:51:17