如何强制任务停止? [英] How do I force a Task to stop?

查看:89
本文介绍了如何强制任务停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用提供了CancellationTokenSourceTask,在我的任务中,我始终检查是否请求取消,并在请求控制的部分停止执行(如果请求).问题在于,在此任务中,我使用了不支持取消的库中运行时间很长的方法,并且这些库是针对.NET 3.5(我使用的是4.5.1)进行编译的.

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).

根据输入,这些方法可以运行几分钟(有时超过10分钟).如果结果永远不会被使用,我不想浪费那么多处理.

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.

还有其他方法可以强制终止Task吗?也许我最好在任务中创建一个线程以运行这些方法,并在请求取消时杀死这些线程.

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.

推荐答案

您唯一的选择是将这些不可取消的函数包装在单独的线程中,并在取消时终止该线程.正如其他人所提到的,Thread.Abort是极其不安全的操作.它终止线程,而不允许进行可能需要的任何资源清理.将此作为最后的手段.根据您何时终止程序,程序可能会处于不希望的状态.

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.

这篇关于如何强制任务停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆