Trying to utilize async and await
I am trying to display loading animation while the user waits for information fetching.
I've been struggling for a couple of days to do things the right way.
Of course Http.Get is copied. I didn't write it myself. The loading method has to be modified as well. Description on how to use async and await and Tasks effectively and easily. Any patterns?
Code:
class Program
{
static class Utils
{
public static void Loading(string mess, int spinDelay, ConsoleColor color)
{
if(Console.BackgroundColor != color)
Console.ForegroundColor = color;
int i = 0;
char[] rFrames = { '|', '/', '-', '\' };
char[] lFrames = { '\', '-', '/', '|' };
int rightid = 0, leftid = 3;
while (i < 20)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write($"{lFrames[leftid]} {mess} {rFrames[rightid]}");
rightid = (rightid + 1) % rFrames.Length;
leftid = (leftid + 1) % lFrames.Length;
Thread.Sleep(spinDelay);
Console.Write('\r');
Console.Write(new string(' ', 4 + mess.Length));
Console.Write('\r');
i++;
}
Console.Write('\r');
Console.Write(new string(' ', 4 + mess.Length));
Console.Write('\r');
}
}
static class Http
{
public static async Task<string> Get(string url)
{
using HttpClient client = new HttpClient();
{
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
}
static async Task Main(string[] args) { //I only know that await gives the control back to the caller Console.WriteLine("Hello, World!"); } }
static async Task Main(string[] args) { //I only know that await gives the control back to the caller Console.WriteLine("Hello, World!"); } }
0 Replies