Added: new projects for Asyncs and RaceConditions with implementations of task handling, async programming, and thread safety.
This commit is contained in:
@@ -0,0 +1,10 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
Console.WriteLine("----- Program started -----");
|
||||||
|
|
||||||
|
Task<int> 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<int> 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<int> 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<int> GetRandomNumber2Async()
|
||||||
|
{
|
||||||
|
Task<int> 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);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
@@ -4,6 +4,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Threads", "Threads\Threads.
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tasks", "Tasks\Tasks.csproj", "{BBDCC3D1-235F-407F-B0FC-E6F48F6D16F3}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tasks", "Tasks\Tasks.csproj", "{BBDCC3D1-235F-407F-B0FC-E6F48F6D16F3}"
|
||||||
EndProject
|
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
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
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}.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.ActiveCfg = Release|Any CPU
|
||||||
{BBDCC3D1-235F-407F-B0FC-E6F48F6D16F3}.Release|Any CPU.Build.0 = 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
|
EndGlobalSection
|
||||||
EndGlobal
|
EndGlobal
|
||||||
|
|||||||
@@ -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<int, string> dictionary = new Dictionary<int, string>();
|
||||||
|
// 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<int, string> concurrentDictionary = new ConcurrentDictionary<int, string>();
|
||||||
|
// 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 -----");
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -47,11 +47,64 @@
|
|||||||
// );
|
// );
|
||||||
// task3.RunSynchronously();
|
// task3.RunSynchronously();
|
||||||
|
|
||||||
Task[] tasks = new Task[10];
|
// Task[] tasks = new Task[10];
|
||||||
Random random = new Random();
|
// Random random = new Random();
|
||||||
for (int i = 0; i < tasks.Length; i++)
|
// 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");
|
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}");
|
Console.WriteLine($"ThreadId ({Thread.CurrentThread.ManagedThreadId}): {i}");
|
||||||
Thread.Sleep(random.Next(100, 1000));
|
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");
|
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 -----");
|
Console.WriteLine("----- Program ended -----");
|
||||||
Reference in New Issue
Block a user