Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

The TDLR; on easily managing .NET concurrent asynchronous threads

Originally posted on: http://geekswithblogs.net/ballhaus/archive/2017/06/12/the-tdlr-on-easily-managing-.net-concurrent-asynchronous-threads.aspx

Ever had the requirement for your code to perform some series of background actions, say to query an API for weather data for various locations, but your provider caps you at having only 2 max concurrent connections at any given time? If so, then you’ve already gone through the wealth of information found online for a solution. I’ve seen quite a few myself and yes, they all work just fine!

For me, I like to keep things as simple as possible… so with that in mind and knowing that you’re most likely here looking for quick code samples, here is my TDLR; for handling this type of scenario:

var mockActions = new List
{
    { () => { Console.WriteLine("Get Weather for Zip 1"); Thread.Sleep(1500); Console.WriteLine("Save Results for Zip 1"); } },
    { () => { Console.WriteLine("Get Weather for Zip 2"); Thread.Sleep(1500); Console.WriteLine("Save Results for Zip 2"); } },
    { () => { Console.WriteLine("Get Weather for Zip 3"); Thread.Sleep(1500); Console.WriteLine("Save Results for Zip 3"); } },
    { () => { Console.WriteLine("Get Weather for Zip 4"); Thread.Sleep(1500); Console.WriteLine("Save Results for Zip 4"); } },
    { () => { Console.WriteLine("Get Weather for Zip 5"); Thread.Sleep(1500); Console.WriteLine("Save Results for Zip 5"); } }
};

//Currently only allowing 2 concurrent threads to run at any given time
var threadBroker = new SemaphoreSlim(2); 

Task.WhenAll(mockActions.Select(iAction => Task.Run(() =>
{
    try
    {
        threadBroker.WaitAsync().Wait();
        iAction();
    }
    finally
    {
        threadBroker.Release();
    }
}))).Wait();


Explanation and more in-depth examples coming soon…



This post first appeared on , please read the originial post: here

Share the post

The TDLR; on easily managing .NET concurrent asynchronous threads

×

Subscribe to

Get updates delivered right to your inbox!

Thank you for your subscription

×