Right now, I cannot understand the difference between async and sync code execution in an API. I'd like to see an example of async await usage in C#, that would clearly show me why it's good.
I've tried to create a simple Console App project, that would simulate an API call.
using System.Threading.Tasks;
namespace TestAppConsole
{
internal class Program
{
public static async Task Main()
{
var asyncProcessor = new AsyncDataProcessor();
await asyncProcessor.ProcessDataAsync();
}
}
}
using System;
using System.Threading.Tasks;
namespace TestAppConsole
{
public class AsyncDataProcessor
{
public async Task ProcessDataAsync()
{
var api1Data = await GetDataFromApi1Async();
var api2Data = await GetDataFromApi2Async();
var result = Process(api1Data, api2Data);
Console.WriteLine(result);
}
private async Task<string> GetDataFromApi1Async()
{
// Simulate an asynchronous API call
await Task.Delay(2000);
return "Data from API 1";
}
private async Task<string> GetDataFromApi2Async()
{
// Simulate another asynchronous API call
await Task.Delay(2000);
return "Data from API 2";
}
private string Process(string data1, string data2)
{
// Simulate data processing
return $"Processed: {data1} and {data2}";
}
}
}
I thought that execution would take around 2s, but it still takes 4s, as in sync code.
Explain to me, please, how can I see the difference between async and sync code in WebAPI? Or what I've done wrong in my example, so it runs sync instead of async?