简体   繁体   English

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

[英]Pattern to use to handle a event with awaitable method in c#

Like the subject of this post, anybody can suggest me the best way to handle an event fired with an async method in c#? 像这篇文章的主题一样,有人可以建议我最好的方法来处理用c#中的async方法触发的事件吗?

Example

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

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

I noticed this answer Await async with event handler Can it be a solution? 我注意到此答案等待事件处理程序异步它是否可以解决?

Thank you! 谢谢! Lewix wi

Solution of @spender seems the cleanest and it works! @spender的解决方案似乎是最干净的,并且有效! General purpose FromEvent method 通用FromEvent方法

Now my awaitable method with this improvement TaskCompletionSource throws "An attempt was made to transition a task to a final state when it had already completed" becomes: 现在,我对这项任务进行了改进的等待方法TaskCompletionSource抛出“试图在任务完成后将其转换为最终状态的尝试”变成:

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;
}

Thank you! 谢谢! Lewix wi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM