我写下了这几行代码:
public static bool RetryUntilSuccessOrTimeoutAsync(Func<bool> task,
TimeSpan executionTimeout, CancellationToken? token = null) {
var data = new ExecutionContextData(task, executionTimeout, token);
var nonBlockingTask = new Task<bool>(SyncTaskExecutor, data);
nonBlockingTask.Start();
var result = nonBlockingTask.ContinueWith(t => t.Result);
return result.Result;
}
class ExecutionContextData {
private readonly Func<bool> task;
private readonly TimeSpan executionTimeout;
private readonly CancellationToken? cancellationToken;
public ExecutionContextData(Func<bool> task, TimeSpan executionTimeout, CancellationToken? cancellationToken) {
this.cancellationToken = cancellationToken;
this.executionTimeout = executionTimeout;
this.task = task;
}
public Func<bool> Task {
get { return task; }
}
public TimeSpan ExecutionTimeout {
get { return executionTimeout; }
}
public CancellationToken? CancellationToken {
get { return cancellationToken; }
}
}
private static bool SyncTaskExecutor(object executionHelper) {
var context = executionHelper as ExecutionContextData;
Task<bool> newTask =
context.CancellationToken.HasValue ? new Task<bool>(ExecuteTask, context.Task, context.CancellationToken.Value)
: new Task<bool>(ExecuteTask, context.Task);
newTask.Start();
bool timeoutResult = newTask.Wait(context.ExecutionTimeout);
if (timeoutResult)
return newTask.Result;
return false;
}
但据我了解,Result 属性调用会阻止调用者。所以,我很不明白如何完成这个任务:“如何异步执行一个任务,所以如果超时那么它会返回 false 或者它会返回应该一遍又一遍地执行的任务的结果? "