取消/中止C#中的任务 [英] Cancel/Abort a Task in C#

查看:56
本文介绍了取消/中止C#中的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#程序,可以执行一些服务调用.我需要在该程序中添加一些代码,以便能够在单击按钮(winform)时停止这些服务调用(例如,如果调用时间太长而用户感到无聊).

I have a program in C# which does some services calls. I need to add some code in this program in order to be able to stop these services calls if I click on a button (winform) [For example, if the call is too long and the user is bored].

困难在于我无法修改执行调用的代码块.

The difficulty is that I can't modify the blocks of code which do the calls.

为此,我计划对Unity框架进行一些拦截.我想在每次输入服务调用代码块时创建一个Task.然后,如果用户单击我的按钮",则取消此任务.

In order to do so, I've planned to do some Interception with the Unity Framework. I would like to create a Task each time I enter a service-call block of code. Then, cancel this task if the user clicks on my Button.

我已经查看了CancellationToken,但是问题是我无法修改calls-blocks,所以我不能执行 if(ct.IsCancellationRequested) ct.ThrowIfCancellationRequested(); AutoResetEvent&也是如此ManualResetEvent.这些调用并不总是异步的,并且是使用CancellationToken进行的,因此,我认为捕获 OperationCanceledException 是不可能的.

I've looked about CancellationToken but the problem is that I can't modify the calls-blocks, so I can't do if(ct.IsCancellationRequested) or ct.ThrowIfCancellationRequested(); Same thing for the AutoResetEvent & ManualResetEvent. The calls are not always asynchronous and made with a cancellationToken, so catching OperationCanceledExceptionis, I think, impossible.

我还考虑过使用Threads并做一些 Thread.Abort(),但是这种方法似乎每次有人调用时都会杀死幼犬.

I've also looked about using Threads and do some Thread.Abort() but this method seems to kill puppies each time someone calls it.

这是我当前程序的一个示例(拦截尚未实现,我想先在一个调用中对其进行测试):

Here is a sample of my current program (the Interception is not implemented yet, I want to test it on a single call first) :

private void Test()
{
    Task.Factory.StartNew(MyServiceCallFunction); // How to cancel the task when I press a button ?
}

// Can't touch the inside of this function :
private void MyServiceCallFunction()
{
    // Blabla I prepare the datas for the call
    // Blabla I do the call
}

我该怎么做?(我没有义务使用任务)

How can I do that ? (I'm not obliged to use a task)

谢谢

推荐答案

正确"的方法是使用CancellationTokens,但是由于您无法修改运行的代码,所以唯一的其他方法是杀死幼犬并使用Thread.Abort()

The "correct" way to do it is to used CancellationTokens but since you can't modify the running code the only other way is to kill the puppies and use Thread.Abort()

类似的东西:

Thread t;
Task.Factory.StartNew(() =>
    {
        t = Thread.CurrentThread;
        MyServiceCallFunction();
    });

t.Abort();

这篇关于取消/中止C#中的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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