Skip to main content
 首页 » 编程设计

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

2024年02月13日13小虾米

假设我有一个异步方法,它会在发生特定更改时通过事件通知我。目前我可以将事件的信息分配给这样的静态变量:

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

这样我就可以区分不同的方法调用及其对应的事件,而无需使用任何静态字段。

请您参考如下方法:

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