0

Like the subject of this post, anybody can suggest me the best way to handle an event fired with an async method in c#?

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

Community
  • 1
  • 1
Luigino De Togni
  • 157
  • 2
  • 15
  • The answer to this is in the body of [this](http://stackoverflow.com/q/12865848/14357) question. Use a `TaskCompletionSource`. – spender May 26 '16 at 10:06
  • Can you please better/clearly state your problem and what exactly you want to solve? – Tamas Ionut May 26 '16 at 10:40
  • I have implemented an interface to comunicate via bluetooth from app to mobile pos. Now i'm working to implement a class and i would like it exposed simply methods that wait until comunication is performed and completed. Solution of @spender works! Thanks – Luigino De Togni May 26 '16 at 11:00

1 Answers1

2

Solution of @spender seems the cleanest and it works! General purpose FromEvent method

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:

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

Community
  • 1
  • 1
Luigino De Togni
  • 157
  • 2
  • 15
  • Improvements to avoid memory leaks and let to call the method more thank once here http://stackoverflow.com/questions/31787840/taskcompletionsource-throws-an-attempt-was-made-to-transition-a-task-to-a-final – Luigino De Togni May 26 '16 at 11:17
  • This is a borderline [link-only answer](http://meta.stackexchange.com/q/8231/213671). You should expand your answer to include as much information here, and use the link only for reference. – gunr2171 May 26 '16 at 13:55