.net c#取消功能

cancelling a function
2021-09-14
  •  译文(汉语)
  •  原文(英语)

我有一个功能,可以发出几个http请求,并在一个任务中运行.该功能可以在中间中断,因为我无法中止任务,因此我在该功能中添加了一些布尔条件.例子:

public int foo(ref bool cancel)
{
    if(cancel)
    {
        return null
    }
    //do some work...
    if(cancel)
    {
        return null
    }
    //http webrequest
    if(cancel)
    {
        return null
    }
 }

尽管这是一些丑陋的代码,但它的工作效果还不错.

另一个问题是,当我已经执行了Web请求时,我花了一些时间才能获得响应,而功能中断需要花费很多时间(直到我得到响应).

有没有更好的方法让我检查一下?还是我应该使用线程而不是任务?

编辑

我添加了一个取消令牌:声明了cancelationTokenSource,并将其令牌传递给任务

CancellationTokenSource cncelToken = new CancellationTokenSource();
Task t = new Task(() => {foo()},cancelToken.token);

当我做cancelToken.Cancel(); 我仍然在等待响应,并且tsk没有取消.

解决过程1

任务支持取消-请参阅此处.

这是一个简短的摘要.

class Program
{
    static void Main(string[] args)
    {
        var token = new CancellationTokenSource();
        var t = Task.Factory.StartNew(
            o =>
            {
                while (true)
                    Console.WriteLine("{0}: Processing", DateTime.Now);
            }, token);

        token.CancelAfter(1000);
        t.Wait(token.Token);
    }
}

请记住使用提供的取消令牌等待任务.您应该收到一个OperationCanceledException.

速聊1:
但它与我的解决方案类似.唯一的不足是我的任务调用了一个函数,而该函数不知道取消标记.我仍然必须检查是否要求取消.我可以使用cencelation令牌,但是比起我,我仍然不得不等待响应返回.我想在那之前取消它.
速聊2:
并非如此-仅在需要执行一些清除操作时才需要对取消令牌进行轮询.如果没有任何清理,该任务将以静默方式停止执行您的代码.
速聊3:
:)
速聊4:
我编辑了问题,尝试使用取消令牌.@ananthonline
速聊5:
谢谢,效果很好!现在我遇到了另一个问题,我无法重用该任务.当我尝试使用new Task()时,任务仍处于取消状态.当我使用task.factory.startnew()时,它可以创建新任务,但是任务的状态仍然相同.@ananthonline

i have a function that makes a few http requests, and runs in a task. that function can be interrupted in the middle, since i cant abort the task i added some boolean conditions in the function. example:

public int foo(ref bool cancel)
{
    if(cancel)
    {
        return null
    }
    //do some work...
    if(cancel)
    {
        return null
    }
    //http webrequest
    if(cancel)
    {
        return null
    }
 }

thisworked pretty good, although this is quite some ugly code.

another problem is when i already executed the web request, and it takes time for me to get the response than the function cncelation takes a lot of time (till i get a response).

is there a better way for me to check this? or mybe i should use threads instead of task?

edit

i added a cancelation token: declared a cancelationTokenSource, and passed its token to the task

CancellationTokenSource cncelToken = new CancellationTokenSource();
Task t = new Task(() => {foo()},cancelToken.token);

when i do cancelToken.Cancel(); i still wait for the response, and the tsk isnt cancelling.

Solutions1

Tasks support cancellation - see here.

Here's a quick snippet.

class Program
{
    static void Main(string[] args)
    {
        var token = new CancellationTokenSource();
        var t = Task.Factory.StartNew(
            o =>
            {
                while (true)
                    Console.WriteLine("{0}: Processing", DateTime.Now);
            }, token);

        token.CancelAfter(1000);
        t.Wait(token.Token);
    }
}

Remember to wait for the task using the provided cancellation token. You ought to receive an OperationCanceledException.

Talk1:
but its simular to my solution. only thins is that my task calls a function, and that function does not know the cancelation token. i will still have to check if the cancelation is requested. i can use a cncelation token, but than i will still have to waite for the response to come back. i want to cancel it before that.
Talk2:
Not really - the need to poll on the cancellation token is only if you have some cleanup to perform. If there isn't any cleanup the task will silently stop executing your code.
Talk3:
:)
Talk4:
i edited the question, tried using cancelation token. @ananthonline
Talk5:
thanks that worked great! now i got a different problem, i cant reuse the task. when i try to use new Task(), than the task is still in a canceled state. when i use task.factory.startnew() it works in creating the new task, but still the task has the same status. @ananthonline
转载于:https://stackoverflow.com/questions/15576761/cancelling-a-function

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入