laatzen/Common/CommonConsole/Program.cs
2024-06-05 15:43:21 +02:00

72 lines
1.7 KiB
C#

namespace CommonConsole
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public static class Program
{
public static void Main()
{
var classes = new Classes();
for (int i = 0; i < 10; i++)
{
classes.AddClass(i + 1);
}
//classes.ConnectAsync(_ =>
//{
// Console.WriteLine($"\t");
//});
}
}
public class Classes
{
private readonly IList<Class> classes = new List<Class>();
internal void AddClass(Int32 nr)
=> this.classes.Add(new Class(nr));
internal Task ConnectAsync(Action<Task[]> continuationTask, CancellationToken cancellationToken)
=> Task.Factory.ContinueWhenAll(this.CallAsync(x => x.Connect), continuationTask, cancellationToken);
protected Task[] CallAsync(Func<Class, Action> action)
{
var count = this.classes.Count;
var tasks = new Task[count];
for (int i = 0; i < count; i++)
{
tasks[i] = Task.Factory.StartNew(this.classes[i].Connect);
}
return tasks;
}
}
public class Class
{
private readonly Int32 nr;
private readonly Random random;
public Class(Int32 nr)
{
this.nr = nr;
this.random = new Random();
}
protected Int32 Next => this.random.Next(1000, 6000);
internal void Connect()
{
var next = this.Next;
Thread.Sleep(next);
Console.WriteLine($"{this.nr}: {nameof(Connect)} after {next}ms");
}
}
}