区分C#中的异步方法回调

时间:2013-06-26 09:21:58

标签: c# events asynchronous event-handling

我们假设我有一个异步方法,当某个更改发生时通过事件通知我。目前我能够将事件的信息分配给这样的静态变量:

    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");

但是我想将回调值分配给这样的语言环境变量:

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

所以我可以区分不同的方法调用及其相应的事件,而不使用任何静态字段。

2 个答案:

答案 0 :(得分:3)

您可以使用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;

}

然后您可以这样使用它:

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

如果你不想使用async / await机制并想阻止线程获得结果,你可以这样做:

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

答案 1 :(得分:1)

如果扩展EventInfoArgs以包含您需要的数据,那么从asychrnous活动传递,您将无需区分。处理程序实现将知道它需要的一切。

如果您不想这样做,那么object的回复是sender吗?