'Task.WhenAll - async a bit slower than sync
I'm very new to threads. I'm making about 50 OAuth2Client Http calls (implemented as Thread.Wait for simplicity). Method pull_NN_async is not faster than pull_NN. After increasing number of iterations async version time lowered 10% below that of sync version. Still not as expected. Please guide me.
using System.Threading.Tasks;
using System.Collections.Generic;
public class Program
{
internal static List<Task> tasks_list = new List<Task>();
internal static void Main()
{
System.Diagnostics.Debug.WriteLine(read_json_and_pull_NN_Async());
System.Diagnostics.Debug.WriteLine(read_json_and_pull_NN_sync());
}
internal static long read_json_and_pull_NN_Async()
{
var watch = System.Diagnostics.Stopwatch.StartNew();
for (int i=0;i<10;i++)
{
Task x = pull_NN_async();
tasks_list.Add(x);
}
await Task.WhenAll(tasks_list);
watch.Stop();
return watch.ElapsedMilliseconds;
}
internal static long read_json_and_pull_NN_sync()
{
var watch = System.Diagnostics.Stopwatch.StartNew();
for (int i=0;i<10;i++)
{
pull_NN();
}
watch.Stop();
return watch.ElapsedMilliseconds;
}
private static async Task<int> pull_NN_async()
{
await pull_NN();
return 0;
}
private static Task pull_NN()
{
System.Threading.Thread.Sleep(1000); //simulated http OAuth2Client request
return null;
}
}
Solution 1:[1]
You have a fire and forget task and you have a poorly created async method.
Here's your code written properly:
public class Program
{
internal static List<Task> tasks_list = new List<Task>();
internal static async Task Main()
{
System.Diagnostics.Debug.WriteLine(await read_json_and_pull_NN_Async());
System.Diagnostics.Debug.WriteLine(read_json_and_pull_NN_sync());
}
internal static async Task<long> read_json_and_pull_NN_Async()
{
var watch = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < 10; i++)
{
Task x = pull_NN_async();
tasks_list.Add(x);
}
await Task.WhenAll(tasks_list);
watch.Stop();
return watch.ElapsedMilliseconds;
}
internal static long read_json_and_pull_NN_sync()
{
var watch = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < 10; i++)
{
pull_NN();
}
watch.Stop();
return watch.ElapsedMilliseconds;
}
private static async Task pull_NN_async()
{
await Task.Delay(TimeSpan.FromSeconds(1.0));
}
private static void pull_NN()
{
System.Threading.Thread.Sleep(1000);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Enigmativity |
