Home > Development > SemaphoreSlim – Controlling Concurrency

SemaphoreSlim – Controlling Concurrency


You can control the number of threads that can access a critical region using a SemaphoreSlim. In the example below we use a Semaphore to control that only 3 threads can access the critical area at time. We are limiting concurrency.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Concurrent;

namespace TPLSamples
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Program p = new Program();
            p.TestingSemaphores();

            Console.WriteLine("Press any key to quit...");
            Console.ReadKey();
        }

        public void TestingSemaphores()
        {
            SemaphoreSlim s = new SemaphoreSlim(3);

            Parallel.For(0, 10, value =>
            {
                s.Wait();
                Thread.Sleep(3000);
                Console.WriteLine(value + " inside semaphore");
                s.Release();
            });
        }
    }
}

Blair….

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: