超时使用TaskCompletionSource实现的异步方法

Ric*_*bob 19 c# asynchronous timeout async-await taskcompletionsource

我有一个blackbox对象,它暴露了一个异步操作的方法,并在操作完成时触发一个事件.我已经将它包装到一个Task<OpResult> BlackBoxOperationAysnc()使用TaskCompletionSource 的方法中 - 效果很好.

但是,在那个异步包装器中,如果在给定的超时后没有收到事件,我想管理用超时错误完成异步调用.目前我使用计时器管理它:

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;
}
Run Code Online (Sandbox Code Playgroud)

这是管理超时的唯一方法吗?有没有设置我自己的计时器 - 我在TaskCompletionSource中看不到任何超时?

nos*_*tio 34

你可以使用CancellationTokenSource超时.与你一起使用它TaskCompletionSource这样.

例如:

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;
}
Run Code Online (Sandbox Code Playgroud)

更新了,这是一个完整的功能示例:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

可以在这里找到.NET 4.0/C#4.0版本,它利用了编译器生成的IEnumerator状态机.

  • 在我看来,您正在使用 CancellationTokenSource 而不是仅运行延迟任务。在 .NET 4.5 中,我更喜欢 Task.Factory.StartNewDelayed(20000, () =&gt; tcs.TrySetCanceled()) 以提高可读性。 (2认同)
  • @AndreasLarsen,这需要`ParallelExtensionsExtras`,但如果你愿意,可以随意发表自己的答案. (2认同)
  • 谢谢你的代码!但是我不得不用tcs.TrySet替换所有tcs.Set*,因为有很多种情况,tcs已经设置为最终状态,导致InvalidOperationException (2认同)