Home > database >  Task.Run() difference for awaitable Task
Task.Run() difference for awaitable Task

Time:01-15

I have been trying to find out what is the difference between.

Task.Run(() => DoSomething());

and

 Task.Run(async() => await DoSomething());

I have been testing this and it does not look like it affects functionality. I am really confused which one to use if you want to run a task. I am calling awaitable task is this just a syntax sugar or is there a difference between those. Which one I should use and why? I am really curious because even if I store that task in a variable it still returns a Task for both cases.

and also we have asynchronous method

   private async Task DoSomething()
        {
     //do something here
        }

I found a great post here await Task.Run vs await explaining specific case of awaiting an async method in the event handler of a GUI application, but that explains only the difference between this

await Task.Run(async () => await LongProcessAsync());

and this

await LongProcessAsync();

CodePudding user response:

Lambda expressions create private methods under the hood. So this:

Task.Run(() => DoSomething());

becomes something like this:

Task.Run(__lambda);
private Task __lambda() => DoSomething();

So, asking what the difference is between these two lines:

Task.Run(() => DoSomething());
Task.Run(async() => await DoSomething());

is the same as asking what the difference is between these two methods:

private Task __lambda() => DoSomething();
private async Task __lambda() => await DoSomething();

I have a blog post that goes into detail. The summary answer is that if all you are doing is just calling DoSomething, then you can elide (remove) the async and await keywords. If the lambda is doing anything else (e.g., modifying arguments) that was removed from your question for simplicity, then I'd recommend keeping the async and await keywords.

As a general guideline: any trivial code can elide async/await; any logic should use async and await.

  •  Tags:  
  • Related