I have read that a 'BackgroundWorker' is designed to be replaced by Ansyc/Await.
Because I like the condensed look of Async/Await, I am starting to convert some of my BackgroundWorkers into Async/Await calls.
This is an example of the code I have (called from the UI):
public async void RunFromTheUI()
{
await OtherAction();
}
public async void OtherAction()
{
var results = await services.SomeRemoteAction();
foreach (var result in results)
{
result.SemiIntenseCalculation();
Several();
Other();
NonAsync();
Calls();
}
SomeFileIO();
}
When I call RunFromTheUI
it will return almost immediately (as per the Async and Await design).
But when it resumes after services.SomeRemoteAction()
finishes it has a foreach
loop and another method call to run through.
My question is: If that loop is a performance hog will it freeze the UI? (Before I had it all in a Background worker thread, so it did not slow the UI down).
Note: I am targeting .Net 4.0 and using the Async Nuget Package.
Async/await helps you write synchronous-looking JavaScript code that works asynchronously. Await is in an async function to ensure that all promises that are returned in the function are synchronized. With async/await, there's no use of callbacks.
The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.
The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains. Async functions may also be defined as expressions.
If a method is declared async, make sure there is an await! If your code does not have an await in its body, the compiler will generate a warning but the state machine will be created nevertheless, adding unnecessary overhead for an operation that will actually never yield.
My question is: If that loop is a performance hog will it freeze the UI?
Yes, it will. The rest of the async method will still execute on the UI thread when the remote action has completed. If you don't want that to happen, then the options are:
ConfigureAwait(continueOnCapturedContext: false)
so that the continuation doesn't execute on the UI threadTask.Run
. (You could still make it an async method, to avoid blocking a thread when you didn't need to.)Basically, if you've got a load of either synchronous, blocking calls or CPU-intensive work, you want to avoid that happening on the UI thread, which is the opposite of what async
/await
does for you by default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With