异步方法上的事件订阅 [英] Event subscription on async method

查看:80
本文介绍了异步方法上的事件订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以两种方式启动LoadDataAsync.首先是通过FormLoad()中具有预订的事件,并通过经典方法ManualLoad().

I wanna launch the LoadDataAsync in 2 ways. First by an event with the subcription in FormLoad() and by a classic method ManualLoad().

但是我无法使其正常工作.

But I can't make it work.

我无法在任务返回时进行订阅.使用void可以使用,但是使用void不能使用ManualLoad()方法中的await.两种方式如何起作用?

I can't make subscription on task return. With void it's works, but with void can't await in the ManualLoad() method. How make both ways work?

    public delegate void ProductDelegate(long? iShopProductId);
    public event ProductDelegate ProductSelectionChanged = delegate { };

    public async Task LoadDataAsync(long? iProductId)
    {
        //await action....
    }

    //first way
    public void FormLoad()
    {
        this.ProductSelectionChanged += LoadDataAsync //UNDERLINED ERROR;
    }

    //second way
    public async Task ManualLoad()
    {
        await LoadDataAsync(2);
    }

推荐答案

由于事件不支持async Task,您需要通过包装"解决该问题,例如:

As events do not support async Task you neeed to work around that via "wrapping" it, e.g.:

this.ProductSelectionChanged += async (s, e) => await LoadDataAsync();

在这里,我创建了一个带有async void签名的匿名方法/处理程序,该签名然后没有执行其他操作await任务返回LoadDataAsync-方法(可以添加ConfigureAwait(false),具体取决于您的特定用例) ).

Here I created an anonymous method/handler with a signature of async void which does nothing else then await the task-returning LoadDataAsync-method (may you should add ConfigureAwait(false), depending on your specific use case).

这篇关于异步方法上的事件订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆