简体   繁体   中英

How to use async/await to delay task without blocking UI

I know I am asking an exist question. I read many articles about this but I still confused. Maybe my English skill is not good enough.

Here is my code at first:

void dovoid1(){
//dosomething
}
void dovoid2(){
//dosomething
}
void dovoid3(){
//dosomething
}

and

void action()
{
            dovoid1();
            Thread.Sleep(1000);
            dovoid2();
            Thread.Sleep(1000);
            dovoid3();
            Thread.Sleep(1000);
            action();
}

As you see, the void action() will do some task, and have a sleep between them. Afer that, it repeat itself. Now I want to avoid Thread.Sleep() because it blocks the UI. So I try to use async/await.

private async void action()
        {

            dovoid1();
            Task.Delay(1000);
            dovoid2();
            Task.Delay(1000);
            dovoid3();
            Task.Delay(1000);
            action();
        }

But it give me errors. I don't know where and When I should use async or await. Thank you!

You need to await the delays to create the desired time gap between calls. Await in this context yields control until Task.Delay completes.

Also, if action() is not an event handler then it should probably be async Task instead of async void (see why is void async bad? ).

private async Task action()
{
    dovoid1();
    await Task.Delay(1000);
    dovoid2();
    await Task.Delay(1000);
    dovoid3();
    await Task.Delay(1000);
    action();
}

you can use this approach in your parent function for non-blocking your UI

await Task.Run(() => {
    // Do lot of work here
});

in your case

await Task.Run(() => action());

if your action method is async

async Task action(){}

then

await Task.Run(async () => await action());

you can simply convert your action method to async by putting await keyword on every Task. Since await keyword can only be used with async method, You need to convert your method to async.

async Task action()
{
            dovoid1();
            await Task.Delay(1000);
            dovoid2();
            await Task.Delay(1000);
            dovoid3();
            await Task.Delay(1000);
            action();
}

please keep in mind that if your dovoid1, dovoid2, dovoid3 includes Task then they are also needed to be converted to async method and needed to be awaited.

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