C
C#2mo ago
Robert

Task.Run() in .net framework

Hi, I'm maintaining an older legacy .net Framework application in which I have a void start() method (that must be void, however now this is intertwined with async await)
public async Task ConnectToSomeService() { ... }

public void StartService()
{
// what's the right way to call this here
Task.Run(ConnectToSomeService);
Task.Run( async () => await ConnectToSomeService());
ConnectToSomeService(); // and disable the warning ;)
}
public async Task ConnectToSomeService() { ... }

public void StartService()
{
// what's the right way to call this here
Task.Run(ConnectToSomeService);
Task.Run( async () => await ConnectToSomeService());
ConnectToSomeService(); // and disable the warning ;)
}
as far as i understand async () => await is slower but i don't quite grasp the difference.
3 Replies
coffeeisntforkitties♡
Here's some people who explained it better than I can: https://stackoverflow.com/questions/34755819/async-await-action-within-task-run
Stack Overflow
Async/Await action within Task.Run()
Task.Run(()=>{}) puts the action delegate into the queue and returns the task . Is there any benefit of having async/await within the Task.Run()? I understand that Task.Run() is required since i...
Robert
RobertOP2mo ago
Thank you!
Thalnos
Thalnos2mo ago
The right way to call it is the second way you‘ve given because ConnectToSomeService is an async method that returns a Task. If it was a synchronous method you‘d use the first way

Did you find this page helpful?