用于在c#中使用等待方法处理事件的模式

时间:2016-05-26 10:04:21

标签: c# events asynchronous

就像这篇文章的主题一样,任何人都可以建议我使用c#中的异步方法处理事件的最佳方法吗?

实施例

// Before:
MyPosClass.EventBluetoothCommunicationCompleted+= (sender, ErrorCode) =>
            {
                // implementation on event fired
            };

// After:
var result = await MyPosClass.WaitBluetoothCommunicationCompleted();

我注意到了这个答案 Await async with event handler 它可以成为解决方案吗?

谢谢! Lewix

1 个答案:

答案 0 :(得分:0)

@spender的解决方案似乎最干净且有效! General purpose FromEvent method

现在我的等待方法 有了这种改进TaskCompletionSource throws "An attempt was made to transition a task to a final state when it had already completed" 变为:

public Task<TransactionData> PerformTransactionAwait()
{
    var tcs = new TaskCompletionSource<TransactionData>();

    EventHandler<TransactionInfo> callback = null;
    callback = (sender, TransactionDataResult) =>
    {
        MyInterface.TransactionPerformed -= callback;
        tcs.SetResult(TransactionDataResult);
    };

    MyInterface.TransactionPerformed += callback;
    MyInterface.PerformTransactionAsync();

    return tcs.Task;
}

谢谢! Lewix