Korzystanie Zadania dla niestandardowego limit czasu na metody Async
Oto moja implementacja niestandardowej klasy z metodą zawinąć zadanie mieć timeout .
public class TaskWithTimeoutWrapper
{
protected volatile bool taskFinished = false;
public async Task<T> RunWithCustomTimeoutAsync<T>(int millisecondsToTimeout, Func<Task<T>> taskFunc, CancellationTokenSource cancellationTokenSource = null)
{
this.taskFinished = false;
var results = await Task.WhenAll<T>(new List<Task<T>>
{
this.RunTaskFuncWrappedAsync<T>(taskFunc),
this.DelayToTimeoutAsync<T>(millisecondsToTimeout, cancellationTokenSource)
});
return results[0];
}
public async Task RunWithCustomTimeoutAsync(int millisecondsToTimeout, Func<Task> taskFunc, CancellationTokenSource cancellationTokenSource = null)
{
this.taskFinished = false;
await Task.WhenAll(new List<Task>
{
this.RunTaskFuncWrappedAsync(taskFunc),
this.DelayToTimeoutAsync(millisecondsToTimeout, cancellationTokenSource)
});
}
protected async Task DelayToTimeoutAsync(int millisecondsToTimeout, CancellationTokenSource cancellationTokenSource)
{
await Task.Delay(millisecondsToTimeout);
this.ActionOnTimeout(cancellationTokenSource);
}
protected async Task<T> DelayToTimeoutAsync<T>(int millisecondsToTimeout, CancellationTokenSource cancellationTokenSource)
{
await this.DelayToTimeoutAsync(millisecondsToTimeout, cancellationTokenSource);
return default(T);
}
protected virtual void ActionOnTimeout(CancellationTokenSource cancellationTokenSource)
{
if (!this.taskFinished)
{
cancellationTokenSource?.Cancel();
throw new NoInternetException();
}
}
protected async Task RunTaskFuncWrappedAsync(Func<Task> taskFunc)
{
await taskFunc.Invoke();
this.taskFinished = true;
}
protected async Task<T> RunTaskFuncWrappedAsync<T>(Func<Task<T>> taskFunc)
{
var result = await taskFunc.Invoke();
this.taskFinished = true;
return result;
}
}
Następnie można nazwać tak:
await new TaskWithTimeoutWrapper().RunWithCustomTimeoutAsync(10000,() => this.MyTask());
lub
var myResult = await new TaskWithTimeoutWrapper().RunWithCustomTimeoutAsync(10000,() => this.MyTaskThatReturnsMyResult());
I można dodać znak anulowania, jeśli chcesz, aby anulować uruchomione zadanie asynchronicznej jeśli dojdzie do koniec czasu.
Nadzieja pomaga
będziemy chcieli patrzeć na [Stoper] (http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) klasy. [Tutaj] (http://stackoverflow.com/a/5019172/95573) to przykład: – SwDevMan81
Co robi "tryMethod"? W powyższym kodzie twoje polecenie if zostanie osiągnięte dopiero po zakończeniu "trymethod". – JMK
To wydaje się być czymś, co możesz chcieć wykonać asynchronicznie? – emd