Skip to content

Instantly share code, notes, and snippets.

@ChaseFlorell
Created April 26, 2017 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChaseFlorell/cbb2ad05228689e8cd1edb8f555b9e8b to your computer and use it in GitHub Desktop.
Save ChaseFlorell/cbb2ad05228689e8cd1edb8f555b9e8b to your computer and use it in GitHub Desktop.
How to run two processes simultaneously.
var loopCanceller = new CancellationTokenSource();
HttpResponseMessage response = null;
var loop = Progress.ProgressDots(loopCanceller.Token);
var send = Task.Run(async () =>
{
response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
loopCanceller.Cancel(false);
});
await Task.WhenAll(send, loop);
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Utils
{
public static class Progress
{
public static Task ProgressDots(CancellationToken token)
{
return ProgressDots(token, 2000);
}
public static async Task ProgressDots(CancellationToken token, int msDelay)
{
try
{
await Task.Run(async () =>
{
var dots = ".";
while (!token.IsCancellationRequested)
{
Console.Write($"\r{dots}");
var trimmedLength = dots.Replace("\r", "").Replace("\n", "").Length;
if (trimmedLength%Console.WindowWidth == 0)
{
Console.WriteLine();
dots = "";
}
dots += ".";
await Task.Delay(msDelay, token);
}
},
token);
}
catch
{
/* gulp - task cancelled*/
}
}
public static Task ProgressSpinner(CancellationToken token)
{
return ProgressSpinner(token, 100);
}
public static async Task ProgressSpinner(CancellationToken token, int msDelay)
{
try
{
await Task.Run(async () =>
{
while (!token.IsCancellationRequested)
{
var arr = new[] {"\\", "|", "/", "-"};
foreach (var a in arr)
{
Console.Write($"\r {a}");
await Task.Delay(msDelay, token);
}
}
},
token);
}
catch
{
/* gulp - task cancelled */
}
finally
{
Console.Write("\r ");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment