简体   繁体   中英

OnContextItemSelected async call

Problem

I override the method bool OnContextItemSelected(IMenuItem item) in Xamarin Android to catch when the user clicks on a context menu.

When the user click on a specific item in the menu, I call a webservice to remove some information related to the row clicked.

I want to remove the information without blocking the UI thread, but still have control of the execution. Do you have any ideas? Any Task black magic? :-)

Constraints

1) I cannot use the async keyword in OnContextItemSelected because it would change the return type from bool to Task

2) The webservice call should not block the UI thread.

Attemped solutions

1) Changing the return type to Task and somehow still override the method.

2) Using Task task = Task.Run(async () => ....) and then Task.Wait()

3) Using Task task = Task.Run(async () => ... ) without wait. I works but I have no control of when the task is completed.

Example code

public override bool OnContextItemSelected(IMenuItem item)
{
            if (item.ItemId == Resource.Id.delete)
            {
                   ...
                   //Call webservice without blocking the UI thread
            }
}

I'd suggest you implement another async method that you call from your event handler:

private async Task TellWebServiceToRemoveAsync()
{
    await webService.RemoveAsync(); // or whatever it's called
    // do what you need to do when webservice has finished
    // this will happen on the UI thread again
}

public override bool OnContextItemSelected(IMenuItem item)
{
    if (item.ItemId == Resource.Id.delete)
    {
        TellWebServiceToRemoveAsync();
        return true;                   
    }
}

The compiler turns TellWebServiceToRemoveAsync() into a state machine . At the await keyword the control flow is returned to the caller (your event handler and from there to the UI).

When the asynchronous webservice call is completed, the execution of TellWebServiceToRemoveAsync() is resumed after the await keyword, but on the UI thread .

So you can manipulate your UI controls from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM