Dear Frank Nátán,
Thank you for your question about ASP.NET APIs written in C#. I assume you are not referring to .NET Core, so I am advising you by using .NET 4.8 Web API in my sample solution. I did not use any .NET Core functionality.
I understand that your synchronous function you've written is to run the function LogicA synchronously, then run LogicB without waiting, and then return an Ok response to the browser. I am assuming LogicB is not resource-intensive or in need of being broken into parallel processes. I am also assuming LogicB will in some way, shape, or form perform any action required in your application until a later process, which you've not provided and I cannot address without more details.
Please see my Proof-of-Concept with in-line comments to describe the logic as best I can. Please let me know if you have additional questions.
/// <summary>
/// Initial code provided by user asking question
/// </summary>
/// <param name="request">Object used in Proof-of-Concept</param>
/// <returns>An ActionResult object</returns>
public IActionResult MyWebApiMethod(HttpRequest request)
{
// Let's see what thread we're running on just for fun
GetCurrentThread();
// synchronous proof-of-concept
LogicA(request);
// asynchronous proof-of-concept - runs in new thread, thus not blocking this one
// refer to https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming for some best-practices
Task.Run(() => LogicB(request));
Console.WriteLine("I'm gonna go return OK to my caller now! The rest is up to you to handle, young padawan. :)");
GetCurrentThread();
// code from original question
return Ok(request);
}
private static void GetCurrentThread()
{
Console.WriteLine(Thread.CurrentThread);
}
private async Task LogicB(HttpRequest request)
{
Console.WriteLine("Begin Logic B");
GetCurrentThread();
await Task.Delay(10000);
Console.WriteLine(request.Url);
Console.WriteLine("End Logic B");
}
/// <summary>
/// Demonstration of a syncronous function
/// </summary>
/// <param name="request">The object to perform actions on</param>
private void LogicA(HttpRequest request)
{
Console.WriteLine("Begin Logic A");
GetCurrentThread();
Thread.Sleep(2500);
Console.WriteLine(request.Url);
Console.WriteLine("End Logic A");
}