Julian50
Julian50

Reputation: 2582

Event subscription on async method

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

Upvotes: 9

Views: 8222

Answers (1)

Christoph Fink
Christoph Fink

Reputation: 23093

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

Upvotes: 15

Related Questions