I just learned some more about async await. I used to think everything in an async Task method just gets executed on a background thread. Now I understand that's not the case and went to refactor some of my code so its blocking less of my UIThread (WPF).
This is my "normal" async method:
public async Task<List<Data>> DoSomethingAsync(){
var data = dbContext.Data.ToListAsync(); // <- Executes on a background thread internally
... // <- Executes on UIThread
return dataList;
}
If I call that method in a ViewModel now, it will not actually be executed on a background. To do that I have to call Task.Run(DoSomethingAsync);.
I didnt want to just blindly wrap all my calls to async methods into Task.Run, so I found myself checking the implementation of every single method whether it has "..." content or is just wrapping an async method from ef core/http/filesystem.
What is the general idea here? Should all my async methods just look like this by default?
public Task<List<Data>> DoSomethingAsyncActuallyInBackground() {
return Task.Run(() => {
var data = dbContext.Data.ToListAsync();
...
return dataList;
}
}
I feel like the first method is somehow "lying". It says Async, but calling it I have actually no idea whether it is truly asynchronous/non blocking code. Internally ef cores ToListAsync() works on a background thread right? Thats how its possible for it to be non blocking.
I am now realizing that I equate "asynchronous" with "on a background thread / non blocking". Is this even true?
DoSomethingAsyncActuallyInBackgroundis not a good idea . Let IO work be IO work, and if you have crazy cpu bound work that is blocking the UI thread. UseTask.Runstrategically.async/awaitand multithreading. You should consider reading Tasks are (still) not threads and async is not parallel and/or There Is No Thread.ToListAsync()works on a background thread right?" No. "Thats how its possible for it to be non blocking" Again, no. See the two linked blog posts for detailed explanation.