Skip to content

Instantly share code, notes, and snippets.

@SaebAmini
Last active April 4, 2020 08:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SaebAmini/05a2370ee8ad7248e2e037ee3b6ffbae to your computer and use it in GitHub Desktop.
Save SaebAmini/05a2370ee8ad7248e2e037ee3b6ffbae to your computer and use it in GitHub Desktop.
Concurrency with one thread
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Diagnostics;
using System.Timers;
using System.Collections.Generic;
public class Program
{
static Uri SlowApiUrl = new Uri("http://slowwly.robertomurray.co.uk/delay/2000/url/https://saebamini.com");
public async static Task Main()
{
ThreadPool.SetMinThreads(100, 100);
ThreadPool.SetMaxThreads(100, 100);
var timer = new System.Timers.Timer(1000);
timer.Elapsed += PrintThreadPoolThreads;
timer.Start();
var sw = Stopwatch.StartNew();
// await TAPSample.DoSequentialAsync();
await TAPSample.DoConcurrentAsync();
timer.Stop();
sw.Stop();
Console.WriteLine($"The whole thing took {sw.Elapsed.TotalSeconds:F2} seconds");
}
public static class TAPSample
{
public static async Task DoSequentialAsync()
{
for (int i = 0; i < 5; i++)
{
var client = new WebClient();
await client.DownloadStringTaskAsync(SlowApiUrl);
Console.WriteLine($"Task {i} done");
}
}
public static async Task DoConcurrentAsync()
{
var tasks = new List<Task>();
for (int i = 0; i < 5; i++)
{
var client = new WebClient();
var no = i;
tasks.Add(client.DownloadStringTaskAsync(SlowApiUrl).ContinueWith(_ => Console.WriteLine($"{no} done")));
}
await Task.WhenAll(tasks);
}
}
static void PrintThreadPoolThreads(object sender, ElapsedEventArgs e)
{
ThreadPool.GetAvailableThreads(out int availableWorkerThreads, out int availableCpThreads);
ThreadPool.GetMaxThreads(out int maxWorkerThreads, out int maxCpThreads);
Console.WriteLine($"{availableWorkerThreads} out of {maxWorkerThreads} worker threads available");
Console.WriteLine($"{availableCpThreads} out of {maxCpThreads} CP threads available");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment