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
答案 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();
中阅读的任务取消的详细信息