diff --git a/Multithreading/Asyncs/Asyncs.csproj b/Multithreading/Asyncs/Asyncs.csproj new file mode 100644 index 0000000..6c1dc92 --- /dev/null +++ b/Multithreading/Asyncs/Asyncs.csproj @@ -0,0 +1,10 @@ + + + + Exe + net10.0 + enable + enable + + + diff --git a/Multithreading/Asyncs/Program.cs b/Multithreading/Asyncs/Program.cs new file mode 100644 index 0000000..7f92c9f --- /dev/null +++ b/Multithreading/Asyncs/Program.cs @@ -0,0 +1,78 @@ +Console.WriteLine("----- Program started -----"); + +Task randomNumberTask = Task.Run(() => +{ + Console.WriteLine($"Task with ThreadId {Thread.CurrentThread.ManagedThreadId} started"); + Thread.Sleep(1000); + Random random = new Random(); + return random.Next(); +}); + +randomNumberTask.Wait(); // this will block the current thread until the task completes +int randomNumber = randomNumberTask.Result; // get the result from the task + +Console.WriteLine($"Random number: {randomNumber}"); + +Task randomNumberTask2 = GetRandomNumberAsync(); +randomNumberTask2.Wait(); +int randomNumber2 = randomNumberTask2.Result; + +Console.WriteLine($"Random number: {randomNumber2}"); + +int randomNumber3 = await GetRandomNumberAsync(); +Console.WriteLine($"Random number: {randomNumber3}"); + +int randomNumber4 = await GetRandomNumber2Async(); +Console.WriteLine($"Random number: {randomNumber4}"); + +SleepAsync(1000).Wait(); + +Console.WriteLine("----- Program ended -----"); + + + +static Task GetRandomNumberAsync() +{ + return Task.Run(() => + { + Console.WriteLine($"Task with ThreadId {Thread.CurrentThread.ManagedThreadId} started"); + Thread.Sleep(1000); + Random random = new Random(); + return random.Next(); + }); +} + +static async Task GetRandomNumber2Async() +{ + Task randomTask = Task.Run(() => + { + Console.WriteLine($"Task with ThreadId {Thread.CurrentThread.ManagedThreadId} started"); + Thread.Sleep(1000); + Random random = new Random(); + return random.Next(); + }); + + int randomNumber = await randomTask; + return randomNumber; +} + +static async Task SleepAsync(int milliseconds) +{ + Console.WriteLine($"Thread Id before sleep: {Thread.CurrentThread.ManagedThreadId}"); + await Task.Delay(milliseconds); + Console.WriteLine($"Thread Id after sleep: {Thread.CurrentThread.ManagedThreadId}"); +} + +// static async Task DelayedInstantiationAsync(GameObject[] prefabs) +// { +// for (int i = 0; i < prefabs.Length; i++) +// { +// Instantiate(prefabs[i]); +// if (i % 10 == 0) +// { +// // update ui, e.g. progress bar +// await Task.Delay(100); +// // await UniTask.DelayFrame(10); +// } +// } +// } \ No newline at end of file diff --git a/Multithreading/Multithreading.sln b/Multithreading/Multithreading.sln index eecf0ff..81474e4 100644 --- a/Multithreading/Multithreading.sln +++ b/Multithreading/Multithreading.sln @@ -4,6 +4,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Threads", "Threads\Threads. EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tasks", "Tasks\Tasks.csproj", "{BBDCC3D1-235F-407F-B0FC-E6F48F6D16F3}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Asyncs", "Asyncs\Asyncs.csproj", "{D0E509B1-F1F0-4D02-BEE4-7F748DCD931A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RaceConditions", "RaceConditions\RaceConditions.csproj", "{485E8ECA-9F81-48B5-9130-BC78AEA102F7}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -18,5 +22,13 @@ Global {BBDCC3D1-235F-407F-B0FC-E6F48F6D16F3}.Debug|Any CPU.Build.0 = Debug|Any CPU {BBDCC3D1-235F-407F-B0FC-E6F48F6D16F3}.Release|Any CPU.ActiveCfg = Release|Any CPU {BBDCC3D1-235F-407F-B0FC-E6F48F6D16F3}.Release|Any CPU.Build.0 = Release|Any CPU + {D0E509B1-F1F0-4D02-BEE4-7F748DCD931A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D0E509B1-F1F0-4D02-BEE4-7F748DCD931A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D0E509B1-F1F0-4D02-BEE4-7F748DCD931A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D0E509B1-F1F0-4D02-BEE4-7F748DCD931A}.Release|Any CPU.Build.0 = Release|Any CPU + {485E8ECA-9F81-48B5-9130-BC78AEA102F7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {485E8ECA-9F81-48B5-9130-BC78AEA102F7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {485E8ECA-9F81-48B5-9130-BC78AEA102F7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {485E8ECA-9F81-48B5-9130-BC78AEA102F7}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/Multithreading/RaceConditions/Program.cs b/Multithreading/RaceConditions/Program.cs new file mode 100644 index 0000000..89135d2 --- /dev/null +++ b/Multithreading/RaceConditions/Program.cs @@ -0,0 +1,121 @@ +using System.Collections.Concurrent; +using System.Text; + +Console.WriteLine("----- Program started -----"); + +Task[] tasks = new Task[1000000]; +Random random = new Random(); + +// int[] numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +// for (int i = 0; i < tasks.Length; i++) +// { +// tasks[i] = Task.Run(() => +// { +// for (int j = 0; j < numbers.Length; j++) +// { +// Console.WriteLine($"Before ({Thread.CurrentThread.ManagedThreadId}): number[{j}]: {numbers[j]}"); +// +// Thread.Sleep(random.Next(0, 1000)); +// +// // not thread-safe +// // int oldValue = numbers[j]; +// // int newValue = oldValue + random.Next(1, 10); +// // numbers[j] = newValue; +// // +// // Console.WriteLine($"Between ({Thread.CurrentThread.ManagedThreadId}): number[{j}]: {numbers[j]}"); +// // +// // Thread.Sleep(random.Next(0, 1000)); +// // +// // Console.WriteLine($"After ({Thread.CurrentThread.ManagedThreadId}): number[{j}]: {numbers[j]}"); +// +// +// // thread-safe +// // option 1: lock +// lock (numbers) +// { +// int oldValue = numbers[j]; +// int newValue = oldValue + random.Next(1, 10); +// numbers[j] = newValue; +// +// Console.WriteLine($"Between ({Thread.CurrentThread.ManagedThreadId}): number[{j}]: {numbers[j]}"); +// +// Thread.Sleep(random.Next(0, 1000)); +// +// Console.WriteLine($"After ({Thread.CurrentThread.ManagedThreadId}): number[{j}]: {numbers[j]}"); +// } +// +// // option 2: use concurrent collection +// // https://learn.microsoft.com/en-us/dotnet/standard/collections/thread-safe/ +// +// // option 3: use chunks to have no overlapping +// // e.g. using Parallel.For or create own chunks +// } +// } +// ); +// } +// + +// Dictionary dictionary = new Dictionary(); +// for (int i = 0; i < tasks.Length; i++) +// { +// tasks[i] = Task.Run(() => +// { +// lock (dictionary) // lock is one option, the other is to use concurrent collection (here ConcurrentDictionary) +// { +// int key = random.Next(); +// if (!dictionary.ContainsKey(key)) +// { +// // dictionary[key] = $"Thread ({Thread.CurrentThread.ManagedThreadId}) number({key}): {random.Next()}"; +// dictionary.TryAdd(key, $"Thread ({Thread.CurrentThread.ManagedThreadId}) number({key}): {random.Next()}"); +// } +// } +// }); +// } + +// ConcurrentDictionary concurrentDictionary = new ConcurrentDictionary(); +// for (int i = 0; i < tasks.Length; i++) +// { +// tasks[i] = Task.Run(() => +// { +// int key = random.Next(); +// if (!concurrentDictionary.ContainsKey(key)) +// { +// // dictionary[key] = $"Thread ({Thread.CurrentThread.ManagedThreadId}) number({key}): {random.Next()}"; +// concurrentDictionary.TryAdd(key, +// $"Thread ({Thread.CurrentThread.ManagedThreadId}) number({key}): {random.Next()}"); +// } +// }); +// } + +File.Delete("output.txt"); +object fileLock = new object(); +for (int i = 0; i < tasks.Length; i++) +{ + tasks[i] = Task.Run(() => + { + // not thread safe + // File.AppendAllText("output.txt", $"Thread ({Thread.CurrentThread.ManagedThreadId}) number: {random.Next()}\n"); + + // FileStream fs = File.OpenWrite("output.txt"); + // FileStream fs = File.Open("output.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite); + // string s = $"Thread ({Thread.CurrentThread.ManagedThreadId}) number: {random.Next()}\n"; + // fs.Write(Encoding.UTF8.GetBytes(s), 0, s.Length); + // fs.Close(); + // fs.Dispose(); + + // thread safe + lock (fileLock) + { + FileStream fs = File.Open("output.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite); + string s = $"Thread ({Thread.CurrentThread.ManagedThreadId}) number: {random.Next()}\n"; + fs.Write(Encoding.UTF8.GetBytes(s), 0, s.Length); + fs.Close(); + fs.Dispose(); + } + }); +} + + +Task.WaitAll(tasks); + +Console.WriteLine("----- Program ended -----"); \ No newline at end of file diff --git a/Multithreading/RaceConditions/RaceConditions.csproj b/Multithreading/RaceConditions/RaceConditions.csproj new file mode 100644 index 0000000..6c1dc92 --- /dev/null +++ b/Multithreading/RaceConditions/RaceConditions.csproj @@ -0,0 +1,10 @@ + + + + Exe + net10.0 + enable + enable + + + diff --git a/Multithreading/Tasks/Program.cs b/Multithreading/Tasks/Program.cs index 741cd11..f4052b6 100644 --- a/Multithreading/Tasks/Program.cs +++ b/Multithreading/Tasks/Program.cs @@ -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 -----"); \ No newline at end of file