6

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);
    }
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
Julian50
  • 2,462
  • 1
  • 21
  • 30
  • 1
    Possible duplicate of [Asynchronous events in C#](http://stackoverflow.com/questions/27761852/asynchronous-events-in-c-sharp) – Ezequiel Jadib Jan 27 '17 at 13:35

1 Answers1

13

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

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
  • thanks a lot. Just to be perfect for my sample the answer is this.ProductSelectionChanged += async (s) => await LoadDataAsync(s); – Julian50 Mar 13 '15 at 11:24
  • 3
    warning: subscribing via anonymous delegate may potentially introduce bugs when you try to unsubscribe it and re-subscribe it, see this answer: https://stackoverflow.com/questions/8803064/event-unsubscription-via-anonymous-delegate – ender Sep 13 '22 at 10:38