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

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

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

最佳答案

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

关于c# - C#中异步方法回调的区分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17316172/

相关文章:

c# - 什么是 C# Using block ,我为什么要使用它?

c# - 在使用 C# 的 Windows 窗体应用程序中正确使用 OnClick 与 MouseClick 事件

MySQL 监听通知等效

rest - 带有 Location header 的 JAX-RS AsyncResponse.resume()

c# - 用于选择节点的 XPath 查询

c# - 我需要一个可以引用超过 7000 万个 texture2d/vector2 对象集的容器

c# - Returnssasync(null) 在 VS15 中使用 Moq 进行单元测试时创建构建错误

javascript - 等待而不是等待解决 promise

c# - 怎么把a文件夹的文件移到b文件夹

javascript - 在 jQuery 中阻止前一个事件完成之前触发另一个事件?