CancellationTokenSource.CancelAfter not working

安稳与你 提交于 2020-01-11 09:45:52

问题


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

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

Any idea why the CancelAfter never works ?


回答1:


Your Sleep method is ignoring the CancellationToken.

Try something like

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


来源:https://stackoverflow.com/questions/17717625/cancellationtokensource-cancelafter-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!