Event subscription on async method

南楼画角 提交于 2019-12-12 15:04:17

问题


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.

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

回答1:


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

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).



来源:https://stackoverflow.com/questions/29029939/event-subscription-on-async-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!