I have two variations of the code that will be provided below.
The task of the code is as follows: I have two url’s that I make an HTTP Get request on and I want to get content from there.
In the first case, I use Task.WhenAll and pass two asynchronous method calls expecting my tasks to execute in parallel and in different threads.
But judging by the output, all of them are executed in the main thread, its id = 1.
In the second case, I use await and expect my tasks to execute sequentially but concurrently.
Although the very essence of await is to wait for an operation to be executed without blocking the main thread.
Please explain where I am mistaken and which option is preferable for such a task?
Method (same in both cases)
public static async Task<string> FetchDataFromUrl(string url)
{
await Console.Out.WriteLineAsync(Thread.CurrentThread.ManagedThreadId.ToString());
try
{
using (HttpClient client = new HttpClient())
{
return await client.GetStringAsync(new Uri(url));
}
}
catch (Exception ex)
{
await Console.Out.WriteLineAsync(ex.Message);
throw;
}
}
Call of method No. 1
namespace ConsoleApp1
{
internal class Program
{
static async Task Main(string[] args)
{
Console.InputEncoding = System.Text.Encoding.UTF8;
Console.OutputEncoding = System.Text.Encoding.UTF8;
string url1 = "https://jsonplaceholder.typicode.com/posts/1";
string url2 = "https://jsonplaceholder.typicode.com/comments/1";
var results = await Task.WhenAll(FetchDataFromUrl(url1), FetchDataFromUrl(url2));
for (int i = 0; i < results.Length; i++)
{
Console.WriteLine(results[i]);
}
}
}
}
Call of method No. 2
namespace ConsoleApp1
{
internal class Program
{
static async Task Main(string[] args)
{
Console.InputEncoding = System.Text.Encoding.UTF8;
Console.OutputEncoding = System.Text.Encoding.UTF8;
string url1 = "https://jsonplaceholder.typicode.com/posts/1";
string url2 = "https://jsonplaceholder.typicode.com/comments/1";
List<string> results = new List<string>
{
await FetchDataFromUrl(url1),
await FetchDataFromUrl(url2),
};
results.ForEach(x => Console.WriteLine(x));
}
}
}