Skip to content

Instantly share code, notes, and snippets.

@irvanherz
Created July 15, 2023 04:09
Show Gist options
  • Save irvanherz/3cccadac495084452d5c8aa61d54428c to your computer and use it in GitHub Desktop.
Save irvanherz/3cccadac495084452d5c8aa61d54428c to your computer and use it in GitHub Desktop.
Task.WaitAll()
using RestSharp;
using System.Threading;
async Task<string> getResponse(string url)
{
var start = DateTime.Now;
var client = new RestClient();
var request = new RestRequest(url);
var response = await client.GetAsync<ResponseDto>(request);
var end = DateTime.Now;
return $"[{url}] {start} -> {end} : {response?.username}";
}
//////////////////////////////
Console.WriteLine($"[{DateTime.Now}] SYNCHRONOUS INVOCATIONS BEGIN");
var results = new List<string>();
for (int i = 0; i < 50; i++)
{
var result = await getResponse("https://random-data-api.com/api/v2/users");
results.Add(result);
}
Console.WriteLine($"[{DateTime.Now}] SYNCHRONOUS INVOCATIONS END");
foreach (var result in results)
{
Console.WriteLine(result);
}
Console.WriteLine("\n");
//////////////////////////////
Console.WriteLine($"[{DateTime.Now}] ASYNCHRONOUS INVOCATIONS BEGIN");
var tasks = new List<Task<string>>();
for (int i = 0; i < 50; i++)
{
var task = getResponse("https://random-data-api.com/api/v2/users");
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
Console.WriteLine($"[{DateTime.Now}] ASYNCHRONOUS INVOCATIONS END");
foreach (var task in tasks)
{
Console.WriteLine(task.Result);
}
//////////////////////////////
class ResponseDto
{
public int id { get; set; }
public string uid { get; set; }
public string password { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string username { get; set; }
public string email { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment