-2

I have some buttons that begin some fairly heavy work, which means my app freezes when I click the button. What I want the button to do is to begin the heavy task and then carry on without waiting for the task to complete. What is the best way of doing this?

I've experimented a bit with the whole Task concept, but I can't seem to implement it correctly.

  • 3
    Make the event handler `async void`. – Kenneth K. Jul 17 '19 at 19:48
  • @Kenneth [Be careful with `async void`](https://stackoverflow.com/q/12144077/215552)... – Heretic Monkey Jul 17 '19 at 19:50
  • 3
    @KennethK. yes that's correct. By the way this should be the **only** time you use `async void`. If it's anything else than an event handler you should use `async Task` if you don't want to return anything. – Joelius Jul 17 '19 at 19:50
  • @HereticMonkey I see you, and I raise you: [Async/Await Best Practices](https://msdn.microsoft.com/en-us/magazine/jj991977.aspx). – Kenneth K. Jul 17 '19 at 19:53
  • @Joelius if I do this, and add an await keyword to the heavy task, will the button method carry on with its code before the task is completed(that is what I want). – user8288212 Jul 17 '19 at 19:55
  • @Kenneth Sure. All I said was "Be careful". Not "You are wrong" :). Indeed, I upvoted Joelius' comment for precisely that reason. – Heretic Monkey Jul 17 '19 at 19:56
  • When the `await` keyword is observed by the runtime, a continuation is registered, and control returns back to the caller. So yes and no: Your application will not block, but the code following the `await` will not execute until the asynhronous operation completes...as long as you didn't mark that as `void` as well. Only the event handler itself should be `void`. – Kenneth K. Jul 17 '19 at 19:57
  • @user8288212 yes. it will not complete the event handler of course because it is waiting for the task to complete (if you use the `await` keyword) however it will give back control to the UI which allows the application to still be responsive even though it's waiting on something to finish executing. The whole thing is a lot more complicated than that though, so I recommend you read some tutorials/docs about `async/await` if you want to know how it works. – Joelius Jul 17 '19 at 20:11

1 Answers1

0

My personal solution : I normally async the button then ConfigureAwait the call :

public DelegateCommand StartProcessCommand { get; set; }

In your constructor :

StartProcessCommand = new DelegateCommand(async () => await OverrideLocation());


public async Task OverrideLocation()
{
      // you can use ConfigureAwait so it doesn't use the main thread
      await _booService.StopListeningAsync().ConfigureAwait(true);
}
Mouse On Mars
  • 1,086
  • 9
  • 28
LeRoy
  • 4,189
  • 2
  • 35
  • 46