BIT64
New member
- Joined
- Jan 1, 2023
- Messages
- 1
- Programming Experience
- 1-3
Hello,
I am new to async functions and I am wondering why my code is not working. I simply do a for loop where I do amount ++ up to 100 000 000. For my single thread I do a for loop twice.
Then for my async I create a list of task, execute the list and wait for the list to be done.
The problem is it seems to take twice as long for my code to execute in async.
Results of execution
How long for non-async vs async task
Starting the timer for single thread heavy task
The bigTask took this long to execute 2 times 0.2910466
Starting the timer for async thread heavy task
The bigTask took this long to execute 2 times 0.6385708
I am new to async functions and I am wondering why my code is not working. I simply do a for loop where I do amount ++ up to 100 000 000. For my single thread I do a for loop twice.
Then for my async I create a list of task, execute the list and wait for the list to be done.
The problem is it seems to take twice as long for my code to execute in async.
code:
using System;
using System.Threading.Tasks;
using System.Diagnostics; //stop watch functions
using System.Runtime.CompilerServices;
using System.Collections.Generic;
Console.WriteLine("How long for non-async vs async task");
Stopwatch sw = new Stopwatch();
//starting single thread task
Console.WriteLine("Starting the timer for single thread heavy task");
sw.Start();
for (var i = 0; i < 2;i++)
{
bigTask();
}
sw.Stop();
Console.WriteLine("The bigTask took this long to execute 2 times " + sw.Elapsed.TotalSeconds);
sw.Reset();
//starting async thread task
Console.WriteLine("Starting the timer for async thread heavy task");
sw.Start();
//bigTaskAsync();
var task = new List<Task> {bigTaskAsync(),bigTaskAsync()};
await Task.WhenAll(task);
sw.Stop();
Console.WriteLine("The bigTask took this long to execute 2 times " + sw.Elapsed.TotalSeconds);
sw.Reset();
void bigTask()
{
var amount = 0;
for (var i = 0; i < 100_000_000; i++)
{
amount++;
}
}
async Task bigTaskAsync() //to return a value from a task do <value type> EX: async Task<int> bigTaskAsync()
{
var amount = 0;
for (var i = 0; i < 100_000_000; i++)
{
amount++;
}
}
Results of execution
How long for non-async vs async task
Starting the timer for single thread heavy task
The bigTask took this long to execute 2 times 0.2910466
Starting the timer for async thread heavy task
The bigTask took this long to execute 2 times 0.6385708