Skip to content

Instantly share code, notes, and snippets.

@thomastvedt
Created October 16, 2020 06:39
Show Gist options
  • Save thomastvedt/618342d2018f0235bcc7fe96ce7ed673 to your computer and use it in GitHub Desktop.
Save thomastvedt/618342d2018f0235bcc7fe96ce7ed673 to your computer and use it in GitHub Desktop.
async init locker?
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleTasks
{
class Program
{
private static async Task<bool> InitLocker(int taskId, int seconds, CancellationToken cancellationToken)
{
Console.WriteLine($"Task {taskId} started");
for (int i = 0; i < 10; i++)
{
await Task.Delay(100 * seconds);
cancellationToken.ThrowIfCancellationRequested();
if (i % 2 == 0)
{
Console.Write(taskId);
}
}
Console.WriteLine($"Task {taskId} completed");
return true;
}
static async Task Main(string[] args)
{
try
{
Console.WriteLine("Starting a lot of tasks..");
var source = new CancellationTokenSource();
source.CancelAfter(TimeSpan.FromSeconds(25)); // <== timeout 21 seconds
var task1 = InitLocker(1, 8, source.Token);
var task2 = InitLocker(2, 15, source.Token);
var task3 = InitLocker(3, 30, source.Token);
Task<bool>[] all = {task1, task2, task3};
// Task.WaitAll(allTasks, source.Token); <= not async
Console.WriteLine("Setup done, wait for all tasks to complete OR cancel OR timeout");
await Task.WhenAll(all);
Console.WriteLine("All tasks done =) Great success");
}
catch (OperationCanceledException err)
{
Console.WriteLine("Cancelled" + err.Message);
}
catch (Exception err)
{
Console.WriteLine("something else?" + err.Message);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment