Async विधि पर कस्टम समय समाप्ति के लिए कार्य का उपयोग करना
यहाँ एक विधि के साथ एक कस्टम वर्ग की मेरी कार्यान्वयन एक कार्य रैप करने के लिए समय समाप्त करने के लिए ।
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;
}
}
तो फिर तुम इसे इस तरह कॉल कर सकते हैं:
await new TaskWithTimeoutWrapper().RunWithCustomTimeoutAsync(10000,() => this.MyTask());
या
var myResult = await new TaskWithTimeoutWrapper().RunWithCustomTimeoutAsync(10000,() => this.MyTaskThatReturnsMyResult());
और आप एक रद्द टोकन जोड़ सकते हैं अगर आप अगर यह करने के लिए हो जाता है चल रहा async कार्य रद्द करना चाहते हैं समय समाप्त।
आशा है कि यह मदद करता है
आप [स्टॉपवॉच] (http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) वर्ग को देखने के लिए चाहता हूँ। [यहां] (http://stackoverflow.com/a/5019172/95573) एक उदाहरण है – SwDevMan81
'tryMethod' क्या करता है? उपर्युक्त कोड में, आपका if कथन केवल 'trymethod' पूरा होने के बाद ही पहुंचा जाएगा। – JMK
ऐसा लगता है कि आप असीमित रूप से निष्पादित करना चाहते हैं? – emd