我想等待Task<T>完成一些特殊规则: 如果在X毫秒后没有完成,我想向用户显示一条消息。 如果它在Y毫秒后没有完成,我想自动request cancellation。
我可以使用Task.ContinueWith异步等待任务完成(即在任务完成时安排执行操作),但这不允许指定超时。 我可以使用Task.Wait同步等待任务完成超时,但是阻止了我的线程。 如何异步等待任务完成超时?
答案 0 :(得分:480)
这个怎么样:
int timeout = 1000;
var task = SomeOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
// task completed within timeout
} else {
// timeout logic
}
添加:根据对我的回答发表评论的请求,这是一个包含取消处理的扩展解决方案。请注意,将取消传递给任务和计时器意味着可以通过多种方式在您的代码中体验取消,并且您应该确保测试并确信您正确处理了所有这些。不要忘记各种组合,并希望您的计算机在运行时做正确的事情。
int timeout = 1000;
var task = SomeOperationAsync(cancellationToken);
if (await Task.WhenAny(task, Task.Delay(timeout, cancellationToken)) == task)
{
// Task completed within timeout.
// Consider that the task may have faulted or been canceled.
// We re-await the task so that any exceptions/cancellation is rethrown.
await task;
}
else
{
// timeout/cancellation logic
}
答案 1 :(得分:162)
这是一个扩展方法版本,它结合了原始任务完成时取消超时,正如Andrew Arnott在对his answer的评论中所建议的那样。
public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout) {
using (var timeoutCancellationTokenSource = new CancellationTokenSource()) {
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
if (completedTask == task) {
timeoutCancellationTokenSource.Cancel();
return await task; // Very important in order to propagate exceptions
} else {
throw new TimeoutException("The operation has timed out.");
}
}
}
答案 2 :(得分:44)
您可以使用Task.WaitAny
等待多个任务中的第一个。
您可以创建两个额外的任务(在指定的超时后完成),然后使用WaitAny
等待先完成的任务。如果先完成的任务是你的“工作”任务,那么你就完成了。如果首先完成的任务是超时任务,那么您可以对超时做出反应(例如请求取消)。
答案 3 :(得分:18)
这样的事情怎么样?
const int x = 3000;
const int y = 1000;
static void Main(string[] args)
{
// Your scheduler
TaskScheduler scheduler = TaskScheduler.Default;
Task nonblockingTask = new Task(() =>
{
CancellationTokenSource source = new CancellationTokenSource();
Task t1 = new Task(() =>
{
while (true)
{
// Do something
if (source.IsCancellationRequested)
break;
}
}, source.Token);
t1.Start(scheduler);
// Wait for task 1
bool firstTimeout = t1.Wait(x);
if (!firstTimeout)
{
// If it hasn't finished at first timeout display message
Console.WriteLine("Message to user: the operation hasn't completed yet.");
bool secondTimeout = t1.Wait(y);
if (!secondTimeout)
{
source.Cancel();
Console.WriteLine("Operation stopped!");
}
}
});
nonblockingTask.Start();
Console.WriteLine("Do whatever you want...");
Console.ReadLine();
}
您可以使用Task.Wait选项而不使用其他任务阻止主线程。
答案 4 :(得分:13)
这是一个基于最高投票答案的完整工作示例,即:
int timeout = 1000;
var task = SomeOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
// task completed within timeout
} else {
// timeout logic
}
此答案中实现的主要优点是已添加泛型,因此函数(或任务)可以返回值。这意味着任何现有函数都可以包含在超时函数中,例如:
之前:
int x = MyFunc();
后:
// Throws a TimeoutException if MyFunc takes more than 1 second
int x = TimeoutAfter(MyFunc, TimeSpan.FromSeconds(1));
此代码需要.NET 4.5。
using System;
using System.Threading;
using System.Threading.Tasks;
namespace TaskTimeout
{
public static class Program
{
/// <summary>
/// Demo of how to wrap any function in a timeout.
/// </summary>
private static void Main(string[] args)
{
// Version without timeout.
int a = MyFunc();
Console.Write("Result: {0}\n", a);
// Version with timeout.
int b = TimeoutAfter(() => { return MyFunc(); },TimeSpan.FromSeconds(1));
Console.Write("Result: {0}\n", b);
// Version with timeout (short version that uses method groups).
int c = TimeoutAfter(MyFunc, TimeSpan.FromSeconds(1));
Console.Write("Result: {0}\n", c);
// Version that lets you see what happens when a timeout occurs.
try
{
int d = TimeoutAfter(
() =>
{
Thread.Sleep(TimeSpan.FromSeconds(123));
return 42;
},
TimeSpan.FromSeconds(1));
Console.Write("Result: {0}\n", d);
}
catch (TimeoutException e)
{
Console.Write("Exception: {0}\n", e.Message);
}
// Version that works on tasks.
var task = Task.Run(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(1));
return 42;
});
// To use async/await, add "await" and remove "GetAwaiter().GetResult()".
var result = task.TimeoutAfterAsync(TimeSpan.FromSeconds(2)).
GetAwaiter().GetResult();
Console.Write("Result: {0}\n", result);
Console.Write("[any key to exit]");
Console.ReadKey();
}
public static int MyFunc()
{
return 42;
}
public static TResult TimeoutAfter<TResult>(
this Func<TResult> func, TimeSpan timeout)
{
var task = Task.Run(func);
return TimeoutAfterAsync(task, timeout).GetAwaiter().GetResult();
}
private static async Task<TResult> TimeoutAfterAsync<TResult>(
this Task<TResult> task, TimeSpan timeout)
{
var result = await Task.WhenAny(task, Task.Delay(timeout));
if (result == task)
{
// Task completed within timeout.
return task.GetAwaiter().GetResult();
}
else
{
// Task timed out.
throw new TimeoutException();
}
}
}
}
<强>注意事项强>
在给出这个答案之后,通常不是在正常操作期间在代码中抛出异常的好习惯,除非你绝对必须:
如果您绝对无法更改正在调用的功能,请仅使用此代码,以便在特定TimeSpan
之后超时。
此答案实际上仅适用于处理您无法重构以包含超时参数的第三方库库。
如何编写健壮的代码
如果你想编写健壮的代码,一般规则是:
每一个可能无限期阻止的操作都必须超时。
如果您不遵守此规则,您的代码最终会遇到由于某种原因失败的操作,然后它将无限期阻止,并且您的应用程序刚刚永久挂起。
如果在一段时间后出现合理的超时,那么您的应用程序会挂起一段极端的时间(例如30秒),然后它会显示错误并继续其快乐的方式,或者重试。
答案 5 :(得分:8)
使用Timer处理邮件和自动取消。任务完成后,在计时器上调用Dispose,以便它们永远不会触发。这是一个例子;将taskDelay更改为500,1500或2500以查看不同的情况:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
private static Task CreateTaskWithTimeout(
int xDelay, int yDelay, int taskDelay)
{
var cts = new CancellationTokenSource();
var token = cts.Token;
var task = Task.Factory.StartNew(() =>
{
// Do some work, but fail if cancellation was requested
token.WaitHandle.WaitOne(taskDelay);
token.ThrowIfCancellationRequested();
Console.WriteLine("Task complete");
});
var messageTimer = new Timer(state =>
{
// Display message at first timeout
Console.WriteLine("X milliseconds elapsed");
}, null, xDelay, -1);
var cancelTimer = new Timer(state =>
{
// Display message and cancel task at second timeout
Console.WriteLine("Y milliseconds elapsed");
cts.Cancel();
}
, null, yDelay, -1);
task.ContinueWith(t =>
{
// Dispose the timers when the task completes
// This will prevent the message from being displayed
// if the task completes before the timeout
messageTimer.Dispose();
cancelTimer.Dispose();
});
return task;
}
static void Main(string[] args)
{
var task = CreateTaskWithTimeout(1000, 2000, 2500);
// The task has been started and will display a message after
// one timeout and then cancel itself after the second
// You can add continuations to the task
// or wait for the result as needed
try
{
task.Wait();
Console.WriteLine("Done waiting for task");
}
catch (AggregateException ex)
{
Console.WriteLine("Error waiting for task:");
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine(e);
}
}
}
}
}
此外,Async CTP提供了一个TaskEx.Delay方法,该方法将为您分配任务中的计时器。这可以为您提供更多控制,例如在Timer触发时设置TaskScheduler以进行延续。
private static Task CreateTaskWithTimeout(
int xDelay, int yDelay, int taskDelay)
{
var cts = new CancellationTokenSource();
var token = cts.Token;
var task = Task.Factory.StartNew(() =>
{
// Do some work, but fail if cancellation was requested
token.WaitHandle.WaitOne(taskDelay);
token.ThrowIfCancellationRequested();
Console.WriteLine("Task complete");
});
var timerCts = new CancellationTokenSource();
var messageTask = TaskEx.Delay(xDelay, timerCts.Token);
messageTask.ContinueWith(t =>
{
// Display message at first timeout
Console.WriteLine("X milliseconds elapsed");
}, TaskContinuationOptions.OnlyOnRanToCompletion);
var cancelTask = TaskEx.Delay(yDelay, timerCts.Token);
cancelTask.ContinueWith(t =>
{
// Display message and cancel task at second timeout
Console.WriteLine("Y milliseconds elapsed");
cts.Cancel();
}, TaskContinuationOptions.OnlyOnRanToCompletion);
task.ContinueWith(t =>
{
timerCts.Cancel();
});
return task;
}
答案 6 :(得分:7)
使用Stephen Cleary优秀的AsyncEx库,您可以:
TimeSpan timeout = TimeSpan.FromSeconds(10);
using (var cts = new CancellationTokenSource(timeout))
{
await myTask.WaitAsync(cts.Token);
}
TaskCanceledException
将在超时时被抛出。
答案 7 :(得分:6)
解决此问题的另一种方法是使用Reactive Extensions:
public static Task TimeoutAfter(this Task task, TimeSpan timeout, IScheduler scheduler)
{
return task.ToObservable().Timeout(timeout, scheduler).ToTask();
}
在单元测试中使用以下代码进行上述测试,它适用于我
TestScheduler scheduler = new TestScheduler();
Task task = Task.Run(() =>
{
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
Thread.Sleep(1000);
}
})
.TimeoutAfter(TimeSpan.FromSeconds(5), scheduler)
.ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted);
scheduler.AdvanceBy(TimeSpan.FromSeconds(6).Ticks);
您可能需要以下命名空间:
using System.Threading.Tasks;
using System.Reactive.Subjects;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using Microsoft.Reactive.Testing;
using System.Threading;
using System.Reactive.Concurrency;
答案 8 :(得分:3)
这是先前答案的稍微增强的版本。
CancellationToken
,并且在发生超时时,您将获得TimeoutException
而不是OperationCanceledException
。async Task<TResult> CancelAfterAsync<TResult>(Func<CancellationToken, Task<TResult>> startTask, TimeSpan timeout, CancellationToken cancellationToken)
{
using (var timeoutCancellation = new CancellationTokenSource())
using (var combinedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellation.Token))
{
var originalTask = startTask(combinedCancellation.Token);
var delayTask = Task.Delay(timeout, timeoutCancellation.Token);
var completedTask = await Task.WhenAny(originalTask, delayTask);
// Cancel timeout to stop either task:
// - Either the original task completed, so we need to cancel the delay task.
// - Or the timeout expired, so we need to cancel the original task.
// Canceling will not affect a task, that is already completed.
timeoutCancellation.Cancel();
if (completedTask == originalTask)
{
// original task completed
return await originalTask;
}
else
{
// timeout
throw new TimeoutException();
}
}
}
答案 9 :(得分:2)
@ Kevan上面使用Reactive Extensions回答的通用版本。
public static Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout, IScheduler scheduler)
{
return task.ToObservable().Timeout(timeout, scheduler).ToTask();
}
使用可选的计划程序:
public static Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout, Scheduler scheduler = null)
{
return scheduler == null
? task.ToObservable().Timeout(timeout).ToTask()
: task.ToObservable().Timeout(timeout, scheduler).ToTask();
}
BTW:当超时发生时,将抛出超时异常
答案 10 :(得分:1)
创建一个扩展以等待任务或延迟完成,以先到者为准。如果延迟获胜,则抛出异常。
public static async Task<TResult> WithTimeout<TResult>(this Task<TResult> task, TimeSpan timeout)
{
if (await Task.WhenAny(task, Task.Delay(timeout)) != task)
throw new TimeoutException();
return await task;
}
答案 11 :(得分:0)
安德鲁·阿诺特(Andrew Arnott)的答案的几种变体:
如果要等待现有任务并确定它是完成还是超时,但是如果发生超时,则不想取消它:
callback
如果要启动工作任务并在发生超时的情况下取消工作:
public static async Task<bool> TimedOutAsync(this Task task, int timeoutMilliseconds)
{
if (timeoutMilliseconds < 0 || (timeoutMilliseconds > 0 && timeoutMilliseconds < 100)) { throw new ArgumentOutOfRangeException(); }
if (timeoutMilliseconds == 0) {
return !task.IsCompleted; // timed out if not completed
}
var cts = new CancellationTokenSource();
if (await Task.WhenAny( task, Task.Delay(timeoutMilliseconds, cts.Token)) == task) {
cts.Cancel(); // task completed, get rid of timer
await task; // test for exceptions or task cancellation
return false; // did not timeout
} else {
return true; // did timeout
}
}
如果已经创建了一个任务,如果发生超时,则要取消该任务:
public static async Task<T> CancelAfterAsync<T>( this Func<CancellationToken,Task<T>> actionAsync, int timeoutMilliseconds)
{
if (timeoutMilliseconds < 0 || (timeoutMilliseconds > 0 && timeoutMilliseconds < 100)) { throw new ArgumentOutOfRangeException(); }
var taskCts = new CancellationTokenSource();
var timerCts = new CancellationTokenSource();
Task<T> task = actionAsync(taskCts.Token);
if (await Task.WhenAny(task, Task.Delay(timeoutMilliseconds, timerCts.Token)) == task) {
timerCts.Cancel(); // task completed, get rid of timer
} else {
taskCts.Cancel(); // timer completed, get rid of task
}
return await task; // test for exceptions or task cancellation
}
另一条评论,如果没有发生超时,这些版本将取消计时器,因此多次调用不会导致计时器堆积。
sjb
答案 12 :(得分:0)
所以这很古老,但是有一个更好的现代解决方案。不知道需要什么版本的c#/。NET,但这是我的方法:
... Other method code not relevant to the question.
// a token source that will timeout at the specified interval, or if cancelled outside of this scope
using var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5));
using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, timeoutTokenSource.Token);
async Task<MessageResource> FetchAsync()
{
try
{
return await MessageResource.FetchAsync(m.Sid);
} catch (TaskCanceledException e)
{
if (timeoutTokenSource.IsCancellationRequested)
throw new TimeoutException("Timeout", e);
throw;
}
}
return await Task.Run(FetchAsync, linkedTokenSource.Token);
CancellationTokenSource
构造函数采用一个TimeSpan
参数,它将导致该令牌在该间隔过去之后取消。然后,您可以将异步(或同步)代码包装到另一个对Task.Run
的调用中,并传递超时令牌。
这假设您要传递取消令牌(token
变量)。如果您不需要在超时之前取消任务,则可以直接使用timeoutTokenSource
。否则,您创建linkedTokenSource
,如果发生超时,它将取消;如果没有超时,则将或取消。
然后我们只捕获OperationCancelledException
并检查哪个令牌引发了异常,如果超时导致引发异常,则抛出TimeoutException
。否则,我们会抛出。
此外,我在这里使用的是C#7中引入的局部函数,但是您可以轻松地使用lambda或实际函数来达到相同的效果。同样,c#8引入了一种更简单的语法来使用语句,但是这些语句很容易重写。
答案 13 :(得分:-1)
在紧张的网络循环中,我觉得Task.Delay()
任务和其他CancellationTokenSource
的用例对我的用例来说有很多答案。
尽管Joe Hoag's Crafting a Task.TimeoutAfter Method on MSDN blogs令人鼓舞,但出于与上述相同的原因,我还是有点厌倦了使用TimeoutException
进行流控制,因为人们期望超时的频率会更高。
所以我去了,它也处理博客中提到的优化:
public static async Task<bool> BeforeTimeout(this Task task, int millisecondsTimeout)
{
if (task.IsCompleted) return true;
if (millisecondsTimeout == 0) return false;
if (millisecondsTimeout == Timeout.Infinite)
{
await Task.WhenAll(task);
return true;
}
var tcs = new TaskCompletionSource<object>();
using (var timer = new Timer(state => ((TaskCompletionSource<object>)state).TrySetCanceled(), tcs,
millisecondsTimeout, Timeout.Infinite))
{
return await Task.WhenAny(task, tcs.Task) == task;
}
}
示例用例如下:
var receivingTask = conn.ReceiveAsync(ct);
while (!await receivingTask.BeforeTimeout(keepAliveMilliseconds))
{
// Send keep-alive
}
// Read and do something with data
var data = await receivingTask;
答案 14 :(得分:-1)
如果您使用BlockingCollection来安排任务,则生产者可以运行可能长时间运行的任务,并且消费者可以使用内置超时和取消令牌的TryTake方法。
答案 15 :(得分:-1)
我将此处和this answer on another thread的其他答案的想法重新推荐为Try样式的扩展方法。如果您想使用扩展方法,但又避免了超时时的异常,这会很有好处。
public static async Task<bool> TryWithTimeoutAfter<TResult>(this Task<TResult> task,
TimeSpan timeout, Action<TResult> successor)
{
using var timeoutCancellationTokenSource = new CancellationTokenSource();
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token))
.ConfigureAwait(continueOnCapturedContext: false);
if (completedTask == task)
{
timeoutCancellationTokenSource.Cancel();
// propagate exception rather than AggregateException, if calling task.Result.
var result = await task.ConfigureAwait(continueOnCapturedContext: false);
successor(result);
return true;
}
else return false;
}
async Task Example(Task<string> task)
{
string result = null;
if (await task.TryWithTimeoutAfter(TimeSpan.FromSeconds(1), r => result = r))
{
Console.WriteLine(result);
}
}
答案 16 :(得分:-3)
绝对不要这样做,但是如果...我认为没有合理的理由,这是一个选择。
((CancellationTokenSource)cancellationToken.GetType().GetField("m_source",
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance
).GetValue(cancellationToken)).Cancel();