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?