What does Stephen Tuub mean
Do not use Task.Run in the implementation of the method; use Task.Run instead to call the method
Is it possible to use Task.Run to hide the work of CPU binding behind asynchronous methods ( Task return methods). If you need to wrap external code, hide it behind an interface that reflects what this code does. Any asynchronous I / O can (and should) be displayed as Task return methods, and work with CPU binding should be displayed using the corresponding API. Let the consumers of your code decide how to use this code. When you also use the consumer, use Task.Run to run your synchronous code (now wrapped and opened through the interface) , where it is very clear that you are unloading work with a CPU binding . For example, in user interface applications, you should call Task.Run at your user interface level (and not go deep into the BL or even DA levels), where it is very clear that the user interface offloads work with some processors.
Why do you think that I should not call Task.Run in BL? What should I do if I have a ViewModel that refers to the service level BL and BL (in my case itโs a shell).
I think the signature of a method should accurately reflect what this method does. The best I can do is redirect you back to the Clearing Article :
When a developer sees two methods in the winrtLibrary.Login () and winrtLibrary.LoginAsync () APIs , the convention is that they are a naturally asynchronous operation . In other words, the developer expects winrtLibrary.LoginAsync () to be a โnaturalโ implementation and that winrtLibrary.Login () is essentially the synchronous (blocking) equivalent of this operation. This API assumes that winrtLibrary.Login will at some point have a calling thread in anticipation of how it blocks a full operation for a naturally-asynchronous operation.
You can still hide the synchronous code behind the async method and follow the Cleary rule if you sign your method as public Task OffloadLoginToTheThreadPool() . But I think (and, apparently, Cleary too) that the alternative of simply calling Task.Run from the user interface (or controller) is a much better approach and follows Clean Code principles.
source share