ConfusedCoder
ConfusedCoder

Reputation: 103

Async Event Subscription

I am using a third party API and it looks like its written using Event Driven Architecture. I am making an asynchronous call to one of the methods on the API but the response from the method is returned in the event handler only. Hence I have to subscribe to the event and then invoke the method call to the API.

Pseudo-code Example:

private string myValue;

public async Task<string> TestPost()
{
    // Subscribe to event
    api.OnSomeAPIFunctionResponse += EventHandler1;

    await CallAPIFunction(...with some parameters...);

    return myValue;
}

private void EventHandler1(sender, args)
{
    // This is the value I want to return in the previous function
    myValue = args.value;
}

In the code example above myValue is null when I run the application because the event handler code kicks in after the function has returned execution.

How can I make the event handler execute asynchronously before the TestPost function returns.

Please suggest me what can be done here.

Upvotes: 1

Views: 1019

Answers (1)

NeddySpaghetti
NeddySpaghetti

Reputation: 13495

What exactly are you trying to do? You can get the correct value of MYVALUE by calling TestPost.Wait() but that is a blocking operation and calling it form a UI thread may cause a deadlock.

If you are trying to set a value to the result of the function, it may be better to await its result

var myVar = await TestPost();

This link explains a bit more about async/await

EDIT:

In response to your comment, you can use a TaskCompletionSource to achieve what you want. This is untested code, but maybe something like this:

    public Task<string> TestPost()
    {
        var tcs = new TaskCompletionSource<string>();
      // Subscribe to event
      api.OnSomeAPIFunctionResponse += ( (s, e) => tcs.SetResult(args.value));

      CallAPIFunction(...with some parameters....);
      return tcs.Task;
    }

Then you get the result the same way:

var myVar = await TestPost();

TaskCompletionSource allows you to convert older asynchronous APIs to use the task based asynchronous pattern. This in turn allows you to use the functionality provided by the Task Parallel Library and also use the new keywords in .NET 4.5 async and await. It results in much simpler code. You can read more about TaskCompletionSource in this article by Stephen Toub from the Parallel .NET Team

Upvotes: 2

Related Questions