我如何迫使任務停止?

[英]How do I force a Task to stop?


I am using a Task with a CancellationTokenSource provided, and within my task I always check if cancellation is requested and stop executing if requested - in the parts of the code that I control. The problem is that within this task, I use very long running methods from libraries that don't support cancelling and were compiled for .NET 3.5 (I'm using 4.5.1).

我正在使用一個帶有取消標記源代碼的任務,在我的任務中,我總是檢查是否請求取消並在請求時停止執行——在我控制的代碼中。問題是,在這個任務中,我使用了來自不支持取消的庫的非常長時間運行的方法,並為. net 3.5編譯(我使用的是4.5.1)。

Depending on the input, these methods can run for several minutes (sometimes 10+). I don't want to let so much processing go to waste if the result is never going to be used.

根據輸入的不同,這些方法可以運行幾分鍾(有時為10+)。如果結果永遠不會被使用,我不想讓這么多的處理浪費掉。

Is there any other way to forcefully terminate a Task? Perhaps I am better off making a thread within my task just to run these methods, and kill those threads whenever cancellation is requested.

有沒有其他方法可以強行終止任務?也許我最好在任務中創建一個線程來運行這些方法,並在請求取消時終止這些線程。

2 个解决方案

#1


2  

Your only option is to wrap these non-cancelable functions within a separate thread and just terminate that thread upon cancelation. As mentioned by others Thread.Abort is an extremely unsafe operation. It terminates the thread without allowing any resource cleanup that may be needed. Use this as a last resort. Depending on when you abort your program might be left in undesired states.

您唯一的選擇是將這些不可取消的函數包裝在一個單獨的線程中,並在取消時終止該線程。正如其他人提到的那樣。中止是一個非常不安全的操作。它在不允許任何資源清理的情況下終止線程。把這當作最后的手段。根據中止的時間,程序可能處於不希望的狀態。

#2


2  

It depends on your specific implementation, but you can try and make the long operation throw an exception (as long as it handles that well) after a timeout has passed, and catch it in the code you control.

這取決於您的特定實現,但是您可以嘗試在超時過后,並在您控制的代碼中捕獲長操作拋出異常(只要它處理得很好)。

You can find examples in this question: Async network operations never finish

您可以在這個問題中找到示例:異步網絡操作永遠不會完成


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/03/17/72510fb27f4f95affcd735a900898dd4.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com