问题描述
我有一个 blackbox 对象,它公开了一个方法来启动异步操作,并且在操作完成时会触发一个事件.我已经把它包装成一个 TaskBlackBoxOperationAysnc()
方法使用 TaskCompletionSource - 效果很好.
I have a blackbox object that exposes a method to kick of an async operation, and an event fires when the operation is complete. I have wrapped that into an Task<OpResult> BlackBoxOperationAysnc()
method using TaskCompletionSource - that works well.
但是,在该异步包装器中,如果在给定的超时后未收到事件,我想管理完成带有超时错误的异步调用.目前我用计时器管理它:
However, in that async wrapper I'd like to manage completing the async call with a timeout error if the event is not received after a given timeout. Currently I manage it with a timer as:
public Task<OpResult> BlackBoxOperationAysnc() {
var tcs = new TaskCompletionSource<TestResult>();
const int timeoutMs = 20000;
Timer timer = new Timer(_ => tcs.TrySetResult(OpResult.Timeout),
null, timeoutMs, Timeout.Infinite);
EventHandler<EndOpEventArgs> eventHandler = (sender, args) => {
...
tcs.TrySetResult(OpResult.BlarBlar);
}
blackBox.EndAsyncOpEvent += eventHandler;
blackBox.StartAsyncOp();
return tcs.Task;
}
这是管理超时的唯一方法吗?有没有办法不设置我自己的计时器 - 我看不到 TaskCompletionSource 内置的任何超时?
Is that the only way to manage a timeout? Is there someway without setting up my own timer - I couldn't see anything timeout built into TaskCompletionSource?
推荐答案
您可以使用 CancellationTokenSource 超时.将它与您的 TaskCompletionSource
一起使用,例如 this.
You could use CancellationTokenSource with timeout. Use it together with your TaskCompletionSource
like this.
例如:
public Task<OpResult> BlackBoxOperationAysnc() {
var tcs = new TaskCompletionSource<TestResult>();
const int timeoutMs = 20000;
var ct = new CancellationTokenSource(timeoutMs);
ct.Token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: false);
EventHandler<EndOpEventArgs> eventHandler = (sender, args) => {
...
tcs.TrySetResult(OpResult.BlarBlar);
}
blackBox.EndAsyncOpEvent += eventHandler;
blackBox.StartAsyncOp();
return tcs.Task;
}
更新,这是一个完整的功能示例:
Updated, here's a complete functional example:
using System;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication
{
public class Program
{
// .NET 4.5/C# 5.0: convert EAP pattern into TAP pattern with timeout
public async Task<AsyncCompletedEventArgs> BlackBoxOperationAsync(
object state,
CancellationToken token,
int timeout = Timeout.Infinite)
{
var tcs = new TaskCompletionSource<AsyncCompletedEventArgs>();
using (var cts = CancellationTokenSource.CreateLinkedTokenSource(token))
{
// prepare the timeout
if (timeout != Timeout.Infinite)
{
cts.CancelAfter(timeout);
}
// handle completion
AsyncCompletedEventHandler handler = (sender, args) =>
{
if (args.Cancelled)
tcs.TrySetCanceled();
else if (args.Error != null)
tcs.SetException(args.Error);
else
tcs.SetResult(args);
};
this.BlackBoxOperationCompleted += handler;
try
{
using (cts.Token.Register(() => tcs.SetCanceled(), useSynchronizationContext: false))
{
this.StartBlackBoxOperation(null);
return await tcs.Task.ConfigureAwait(continueOnCapturedContext: false);
}
}
finally
{
this.BlackBoxOperationCompleted -= handler;
}
}
}
// emulate async operation
AsyncCompletedEventHandler BlackBoxOperationCompleted = delegate { };
void StartBlackBoxOperation(object state)
{
ThreadPool.QueueUserWorkItem(s =>
{
Thread.Sleep(1000);
this.BlackBoxOperationCompleted(this, new AsyncCompletedEventArgs(error: null, cancelled: false, userState: state));
}, state);
}
// test
static void Main()
{
try
{
new Program().BlackBoxOperationAsync(null, CancellationToken.None, 1200).Wait();
Console.WriteLine("Completed.");
new Program().BlackBoxOperationAsync(null, CancellationToken.None, 900).Wait();
}
catch (Exception ex)
{
while (ex is AggregateException)
ex = ex.InnerException;
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
可以在此处找到 .NET 4.0/C# 4.0 版本,它利用了编译器生成的 IEnumerator
状态机.
A .NET 4.0/C# 4.0 vesion can be found here, it takes advantage of the compiler-generated IEnumerator
state machine.
这篇关于超时使用 TaskCompletionSource 实现的异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!