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,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);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
Reference in New Issue
Block a user