CancellationTokenSource.CancelAfter not working

后端 未结 1 1932
执笔经年
执笔经年 2021-01-21 00:26

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 se

相关标签:
1条回答
  • 2021-01-21 00:58

    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();
    }
    
    0 讨论(0)
提交回复
热议问题