public class HardWorker : AbstractHardWorker
{
public void DoSomething(int time)
{
Thread.Sleep(time);
}
}
static void Main(string[] args)
{
HardWorker hardWorker1 = new HardWorker();
..........................................
HardWorker hardWorker5 = new HardWorker();
Random rand = new Random();
for (int i=0; i < 50; i++)
{
hardWorker1.DoSomething(rand.Next(1,10000));
.......................................
hardWorker5.DoSomething(rand.Next(1,10000));
}
}
class Program
{
static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
Console.ReadKey();
}
static async Task MainAsync(string[] args)
{
HardWorker hardWorker1 = new HardWorker();
HardWorker hardWorker2 = new HardWorker();
HardWorker hardWorker3 = new HardWorker();
HardWorker hardWorker4 = new HardWorker();
HardWorker hardWorker5 = new HardWorker();
Task t1 = Task.CompletedTask;
Task t2 = Task.CompletedTask;
Task t3 = Task.CompletedTask;
Task t4 = Task.CompletedTask;
Task t5 = Task.CompletedTask;
Random rand = new Random();
for (int i = 0; i < 50; i++)
{
t1 = t1.ContinueWith(task => hardWorker1.DoSomething(1, rand.Next(1, 10000)));
t2 = t2.ContinueWith(task => hardWorker2.DoSomething(2, rand.Next(1, 10000)));
t3 = t3.ContinueWith(task => hardWorker3.DoSomething(3, rand.Next(1, 10000)));
t4 = t4.ContinueWith(task => hardWorker4.DoSomething(4, rand.Next(1, 10000)));
t5 = t5.ContinueWith(task => hardWorker5.DoSomething(5, rand.Next(1, 10000)));
}
await Task.WhenAll(t1, t2, t3, t4, t5);
}
}
public class HardWorker : AbstractHardWorker
{
public void DoSomething(int task, int time)
{
Console.Out.WriteLine("Start: " + task);
Thread.Sleep(time);
Console.Out.WriteLine("End: " + task);
}
}
public interface AbstractHardWorker
{
void DoSomething(int task, int time);
}
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace TasksSample
{
public class Worker
{
private int id;
public Worker(int id)
{
this.id = id;
}
public void DoHardWork()
{
Console.WriteLine($"Task {this.id} started.");
Random rng = new Random();
int delay = rng.Next(1000, 10000);
Thread.Sleep(delay);
Console.WriteLine($"Task {this.id} finished after {delay} ms.");
} // DoHardWork
} // class Worker
class Program
{
static void Main(string[] args)
{
TaskFactory fact = new TaskFactory();
int TaskCount = 10;
List<Task> myTasks = new List<Task>();
for (int id = 0; id < TaskCount; ++id)
{
Worker w = new Worker(id);
myTasks.Add(fact.StartNew(() => w.DoHardWork()));
}
Task.WaitAll(myTasks.ToArray());
} // void Main
} // class Program
} // namespace TasksSample