简体   繁体   中英

Async method to update ui executes partially

I'm developing an android app using xamarin and what I'm trying to do is really simple: on the click of a button disable itself for 1 second.

Here's the relevant part of the code I put together:

protected override void OnCreate(Bundle savedInstanceState)
{
//...
        sendShortDataButton.Click += (object sender, EventArgs e) => {
                Task.Run(() => DisableButtonFor());               
            };
//...
        private async Task DisableButtonFor()
        {
            sendShortDataButton.Enabled = false; //<------
            await Task.Delay(1000);
            sendShortDataButton.Enabled = true;
        }
}

The problem here is that, by debugging the app, the code runs only to where the arrow points everything after gets ignored. On the app the button does actually get disabled, so I'm not really sure what's going wrong.

Thanks!

Try this:

sendShortDataButton.Click += async (sender, e) =>
{
    var button = (Button)sender;
    button.Enabled = false;
    await Task.Delay(1000);
    button.Enabled = true;
};

You don't need Task.Run if the only async work you have is to await a Task.Delay . But if you do have more async work to do, then it's better to use Task.Run for this work only:

sendShortDataButton.Click += async (sender, e) =>
{
    var button = (Button)sender;
    button.Enabled = false;
    await Task.Run(async () =>
    {
        await Task.Delay(1000); // Simulate async work
    });
    button.Enabled = true;
};

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