I have an ASP.NET Core 3.1 based project written using C#. I am aware that the best time to use await and async is when accessing external resources like pulling data from the database, accessing files, or making an HTTP request. This frees up the thread so more work is done instead for the thread to sit around waiting for code to finish.
However, I am trying to figure out at what point using async/await will hurt performance? Does the process of releasing the thread when await is called and retrieving a thread when the task complete have cost?
The code found next, is called asynchronously. In reality, that code does not need to be called asynchronously since all the code is executed in memory and no external requests are made.
public interface ILocator
{
Task<Model> ExampleAsync();
}
public class Example : Controller
{
public ILocator Locator { get; set; }
public Example(ILocator locator)
{
Locator = locator;
}
public async Task<IActionResult> Example()
{
Model model = await Locator.ExampleAsync();
return View(model);
}
}
public class Locator : ILocator
{
pubilc Task ExampleAsync()
{
Example model = new Example();
model.Status = "New";
return Task.CompletedTask;
}
}
Here is the synchronous version of the above code
public interface ILocator
{
Model Example();
}
public class Example : Controller
{
public ILocator Locator { get; set; }
public Example(ILocator locator)
{
Locator = locator;
}
public IActionResult Example()
{
Model model = Locator.Example();
return View(model);
}
}
public class Locator : ILocator
{
pubilc Example()
{
Example model = new Example();
model.Status = "New";
}
}
Will the asynchronous version of the code have higher cost/lower performance than the synchronous version due to the unnecessary await/async usage?
When will async/await do more harm than good?