user4205580
user4205580

Reputation: 572

GUI freezes when using async/await

I'm trying to figure out what's wrong with the code below. I thought that using async and await lets me forget about GUI issues such as freezing because some long code is blocking the main thread.

After I click the button, the GUI is responsive until the call to longRunningMethod, as shown below:

 private async void openButton_Click(object sender, RoutedEventArgs e)
 {
    //doing some usual stuff before calling downloadFiles
    Task<int> result = await longRunningMethod(); // async method

    //at this point GUI becomes unresponsive

    //I'm using the result here, so I can't proceed until the longRunningMethod finishes

  }

I can't proceed until the method finishes, because I need the result. Why this code freezes my app?

Upvotes: 3

Views: 3886

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456507

The problem is within longRunningMethod.

What the code is probably doing is some CPU-bound or blocking operation.

If you want to run some CPU-bound code on a background thread, you have to do so explicitly; async won't jump threads automatically:

int result = await Task.Run(() => longRunningMethod());

Note that if longRunningMethod is CPU-bound, it should have a synchronous - not asynchronous - signature.

If longRunningMethod is not CPU-bound (i.e., it's currently blocking), then you need to change the blocking method calls within longRunningMethod to be asynchronous, and call them via await. Then you can make longRunningMethod asynchronous and call it via await as well:

int result = await longRunningMethodAsync();

Upvotes: 8

Related Questions