The Run method allows you to create and execute a task in a single method call and is a simpler alternative to the StartNew method. It creates a task with the following default values: Its cancellation token is CancellationToken.
NET, Task. Run is used to asynchronously execute CPU-bound code. Let's say there is a method which does some CPU-bound work. Example : looping through a large array and doing some complex computation on each element of the array.
The async/await approach in C# is great in part because it isolates the asynchronous concept of waiting from other details. So when you await a predefined method in a third-party library or in . NET itself, you don't necessarily have to concern yourself with the nature of the operation you're awaiting.
To start a task in C#, follow any of the below given ways. Use a delegate to start a task. Task t = new Task(delegate { PrintMessage(); }); t. Start();
Considering the following code:
public void CacheData() { Task.Run((Action)CacheExternalData); Task.Run(() => CacheExternalData()); Task.Run(CacheExternalDataTask); Task.Run(CacheExternalData); } public Task CacheExternalDataTask() { // Long running code return Task.FromResult("Data"); } public void CacheExternalData() { // Long running code }
Why is Task.Run(CacheExternalData)
ambiguous? And Task.Run(CacheExternalDataTask)
is not?
When calling Task.Run
with CacheExternalData
I would have thought it was clear to the compiler that the method does not return a Task
and it should resolve to an Action
?
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