CancellationToken过期3秒后重启任务c#

时间:2017-07-12 05:46:03

标签: c# multithreading

public  void LoadData()
{
    try
    {
        var cst = new CancellationTokenSource(TimeSpan.FromSeconds(3));

        var result = Task.Run(() => LongRunningMethodCall ),cst.Token)
            .ContinueWith(t =>
            {
                switch (t.Status)
                {
                    case TaskStatus.Canceled:
                        LoadData();
                        break;
                    case TaskStatus.RanToCompletion:
                        var result = t.Result;
                        break;
                }


            }, cst.Token,TaskContinuationOptions.OnlyOnRanToCompletion, _uiScheduler);

    }
    catch (Exception ex)
    {                
    }
}

我需要异步调用LoadData()方法,使用TimeOut指定此任务3秒。 如果任务未在3秒内完成,我需要执行Rerty操作10次以获得t.result

1 个答案:

答案 0 :(得分:1)

    public void LoadData()
    {
        string result = null;

        for ( i = 0; i <= 10; i++ )
        {
            try
            {
                var cst = new CancellationTokenSource( TimeSpan.FromSeconds( 3 ) );
                var task = Task.Run( () => LongRunningMethodCall( cst.Token ), cst.Token );
                var result = task.Result;
            }
            catch ( AggregateException ex )
            {
                // Check that all exceptions is a OperationCanceledException
                if ( !ex.InnerExceptions.All( e => e is OperationCanceledException ) )
                    throw ex;
            }
        }
    }

您应该在CancellationToken中处理LongRunningMethodCall以取消任务。任务取消示例:

if ( token.IsCancellationRequested )
   token.ThrowIfCancellationRequested();

有关您在https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-cancel-a-task-and-its-children

中阅读的任务取消的详细信息