wodzu
wodzu

Reputation: 3172

Distinguishing between asynchronous method callbacks in C#

Let's assume I have an async method, which notifies me via an event when a certain change happens. Currently I'm able to assign the event's information to a static variable like this:

    static EventInfo result = null;



    // eventHandler, which assigns the event's result to a locale variable
    void OnEventInfoHandler(object sender, EventInfoArgs args)
    {
       result = args.Info;
    }



    resultReceived += OnEventInfoHandler;        

    // async method call, which fires the event on occuring changes. the parameter defines on what kind of change the event has to be fired
    ReturnOnChange("change");

But I would like to assign the callback value to a locale variable like this:

var result_1 = ReturnOnChange("change1");
var result_2 = ReturnOnChange("change2");

So I could distinguish between different method calls and their corresponding events, without using any static fields.

Upvotes: 1

Views: 116

Answers (2)

YK1
YK1

Reputation: 7622

You can use TaskCompletionSource.

public Task<YourResultType> GetResultAsync(string change)
{
    var tcs = new TaskCompletionSource<YourResultType>();

    // resultReceived object must be differnt instance for each ReturnOnChange call
    resultReceived += (o, ea) => {
           // check error

           tcs.SetResult(ea.Info);
         };

    ReturnOnChange(change); // as you mention this is async

    return tcs.Task;

}

You can then use it this way:

var result_1 = await GetResultAsync("change1");
var result_2 = await GetResultAsync("change2");

If you dont want to use async/await mechanism and want to block the thread for result, you can do this:

var result_1 = GetResultAsync("change1").Result; //this will block thread.
var result_2 = GetResultAsync("change2").Result;

Upvotes: 3

Jodrell
Jodrell

Reputation: 35716

If EventInfoArgs is extended to include the data you require, passed from the asychrnous activity then, you won't need to distinguish. The handler implementation will know everything it needs.

If you don't want to do that, what object are you returning as the sender?

Upvotes: 1

Related Questions