CancellationTokenSource.Cancel不工作

时间:2013-07-18 07:48:06

标签: c# task linqpad

我正在尝试在这篇帖子上实现一些重试逻辑基础(但是有任务) 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片段(因此是“完成”.Dump())

任何想法为什么CancelAfter永远不会起作用?

1 个答案:

答案 0 :(得分:3)

您的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();
}