取消/中止C#中的任务

编程入门 行业动态 更新时间:2024-10-23 10:29:10
本文介绍了取消/中止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#中的任务

本文发布于:2023-11-10 09:43:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575036.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!