How to decouple UI and App logic/Navigation

RussSherlockRussSherlock GBMember ✭✭
edited July 2015 in Xamarin.Forms
    How do I call an eventhandler asynchronously?

async public event EventHandler<AnObject> AddItem;      // Compiles
        ...
    button.Clicked += async (sender, o) =>
    {
        if(AddItem != null) // Do I need this test?
        {
            await AddItem(sender, new AnObject());      // fails - cannot await a void
        }
    };
Tagged:

Best Answer

Answers

  • adamkempadamkemp USInsider, Developer Group Leader mod

    Event handlers are the one officially sanctioned use case for an async void function. An async void function can use await inside it, but a caller cannot use await to wait for it to finish. That means your event invoker, shown above, does not need to be async or use await.

  • RussSherlockRussSherlock GBMember ✭✭

    Version 2: How do I call an eventhandler asynchronously?

    public event EventHandler<AnObject> AddItem;      // Compiles
            ...
        button.Clicked += async (sender, o) =>      // Complains about the lack of await
        {
            if(AddItem != null) 
            {
                AddItem(sender, new AnObject());      // fails - cannot await a void
            }
        };
    

    I get a complaint that async (on the Click handler) is unnecessary.

    Sorry, your answer may have been 100% correct but the two of us here couldn't make any sense of it. Could you give an example based on the above, that runs asynchronously. Not sure where the officially sanctioned async void plays a part. A void cannot be awaited? We're very confused now.

Sign In or Register to comment.