Added: new projects for Asyncs and RaceConditions with implementations of task handling, async programming, and thread safety.

This commit is contained in:
2026-10-14 18:27:04 +02:00
parent 32d95221e6
commit 39a6de6d85
6 changed files with 316 additions and 7 deletions
+85 -7
View File
@@ -47,11 +47,64 @@
// );
// task3.RunSynchronously();
Task[] tasks = new Task[10];
Random random = new Random();
for (int i = 0; i < tasks.Length; i++)
// Task[] tasks = new Task[10];
// Random random = new Random();
// for (int i = 0; i < tasks.Length; i++)
// {
// tasks[i] = Task.Run(() =>
// {
// Console.WriteLine($"Task with ThreadId {Thread.CurrentThread.ManagedThreadId} started");
//
// for (int i = 0; i < 10; i++)
// {
// Console.WriteLine($"ThreadId ({Thread.CurrentThread.ManagedThreadId}): {i}");
// Thread.Sleep(random.Next(100, 1000));
// }
//
// Console.WriteLine($"Task with ThreadId {Thread.CurrentThread.ManagedThreadId} stopped");
// }
// );
// }
//
// // Task.WaitAll(tasks);
// Task.WaitAny(tasks);
// Parallel.For(0, 10000, i =>
// {
// // do whatever you want to do in parallel
// Console.WriteLine($"Task with ThreadId ({Thread.CurrentThread.ManagedThreadId}): {i}");
// });
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
Task task4 = Task.Run(() =>
{
tasks[i] = Task.Run(() =>
Console.WriteLine($"Task with ThreadId ({Thread.CurrentThread.ManagedThreadId}) started");
for (int i = 0; i < 100; i++)
{
Console.WriteLine($"ThreadId ({Thread.CurrentThread.ManagedThreadId}): {i}");
Thread.Sleep(500);
// ct.ThrowIfCancellationRequested(); // throws a OperationCanceledException
if (ct.IsCancellationRequested)
{
// option 1:
// throw new OperationCanceledException(ct);
// option 2:
// tidy up
break;
}
}
Console.WriteLine($"Task with ThreadId ({Thread.CurrentThread.ManagedThreadId}) stopped");
}, ct);
Task[] tasks2 = new Task[10];
Random random = new Random();
for (int i = 0; i < tasks2.Length; i++)
{
tasks2[i] = Task.Run(() =>
{
Console.WriteLine($"Task with ThreadId {Thread.CurrentThread.ManagedThreadId} started");
@@ -59,14 +112,39 @@ for (int i = 0; i < tasks.Length; i++)
{
Console.WriteLine($"ThreadId ({Thread.CurrentThread.ManagedThreadId}): {i}");
Thread.Sleep(random.Next(100, 1000));
// ct.ThrowIfCancellationRequested(); // throws a OperationCanceledException
if (ct.IsCancellationRequested)
{
// option 1:
// throw new OperationCanceledException(ct);
// option 2:
// tidy up
break;
}
}
Console.WriteLine($"Task with ThreadId {Thread.CurrentThread.ManagedThreadId} stopped");
}
}, ct
);
}
// Task.WaitAll(tasks);
Task.WaitAny(tasks);
if (Console.ReadKey().Key == ConsoleKey.A)
{
cts.Cancel();
// after a cancellation, the CancellationTokenSource is no longer usable
cts.Dispose();
cts = null;
}
Thread.Sleep(1000);
if (cts != null)
{
cts.Dispose();
cts = null;
}
Console.WriteLine("----- Program ended -----");