Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.