编程语言
首页 > 编程语言> > CodeGo.net> C#-CancellationTokenSource.Cancel后不工作

CodeGo.net> C#-CancellationTokenSource.Cancel后不工作

作者:互联网

我正在尝试基于此帖子实现一些重试逻辑(但带有任务)
Cleanest way to write retry logic?

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

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

知道为什么CancelAfter永远行不通吗?

解决方法:

您的Sleep方法将忽略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();
}

标签:task,c,linqpad
来源: https://codeday.me/bug/20191123/2064372.html