CancellationTokenSource.Cancel不工作后 [英] CancellationTokenSource.CancelAfter not working

查看:223
本文介绍了CancellationTokenSource.Cancel不工作后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试基于此帖子实现一些重试逻辑(但带有任务) 编写重试逻辑的最简单方法?

I'm trying to implement some retry logic base on this post (but with tasks) Cleanest way to write retry logic?

重试逻辑的想法是然后执行第二个任务,该任务在给定的时间后触发取消操作

The idea for the retry logic is to then to implement a second task that triggers the cancelation after a give amount of time

void Main()
{
    RetryAction(() => Sleep(), 500);
}

public static void RetryAction(Action action, int timeout)
{
    var cancelSource = new CancellationTokenSource();                
    cancelSource.CancelAfter(timeout);

    Task.Run(() => action(), cancelSource.Token);    
}

public static void Sleep() 
{
    System.Threading.Thread.Sleep(5000);
    "done".Dump();
}

上面是linqPad片段(因此为"done" .Dump())

The above is a linqPad snippet (thus the "done".Dump())

您知道取消后为何永远不起作用的任何想法吗?

Any idea why the CancelAfter never works ?

推荐答案

您的Sleep方法忽略了CancellationToken.

Your Sleep method is ignoring the CancellationToken.

尝试类似

public static CancellationTokenSource cancelSource ;

void Main()
{
    RetryAction(() => Sleep(), 500);
}

public static void RetryAction(Action action, int timeout)
{
     cancelSource = new CancellationTokenSource();                
     cancelSource.CancelAfter(timeout);

     Task.Run(() => action(), cancelSource.Token);    
}

public static void Sleep() 
{
    for(int i = 0 ; i< 50; i++)
    {
        "Waiting".Dump();
        System.Threading.Thread.Sleep(100);

        if (cancelSource.IsCancellationRequested)
        {
            "Cancelled".Dump();
            return;
        }
    }
    "done".Dump();
}

这篇关于CancellationTokenSource.Cancel不工作后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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