Semaphorelock Csharp

16 Aug 2020 - Alejandro Piña

SemaphoreLock class is a module to lock execution by tag name with cocurrent degree allowing execute code simultaneusly.

SemaphoreLock is useful when your code needs to handle data cosistency or prevents deathlocks in the target database.

Install

.NET CLI

$ dotnet add package Ultranaco.Threading

.Package Manager

PM> Install-Package Ultranaco.Threading

.Paket CLI

> paket add Ultranaco.Threading

Usage

The example code below lock the execution main for each semaphore name allowing concurrency degree by tag name

using (var semaphore = new SemaphoreLock("[tableName] + [primaryKey]", 2))
{
  // Do Stuff
}

Example code complete

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Ultranaco.Threading;

namespace RadioHunter
{
  class Program
  {
    static void Main(string[] args)
    {
      var tasks = new List<Task>();

      for (var i = 1; i <= 9; i++)
      {
        var semaphoreName = i % 2 == 0 ? "semaphore-1" : "semaphore-2";
        tasks.Add(Task.Factory.StartNew(HeavyWorkload, semaphoreName));
      }

      Task.WaitAll(tasks.ToArray());
    }

    static void HeavyWorkload(object name)
    {
      var semaphoreName = (string)name;
      Console.WriteLine($@"Start - ThreadID: {Task.CurrentId} Semaphore: {semaphoreName}  time:{DateTime.Now.ToString("mm:ss.ffff")}");

      using (var semaphore = new SemaphoreLock(semaphoreName, 2))
      {
        Thread.Sleep(1000);
      }

      Console.WriteLine($@"Released - ThreadID: {Task.CurrentId} Semaphore: {semaphoreName}  time:{DateTime.Now.ToString("mm:ss.ffff")}");
    }
  }
}

Ouput

Start - ThreadID: 7 Semaphore: semaphore-2  time:11:53.8862
Start - ThreadID: 4 Semaphore: semaphore-1  time:11:53.8862
Start - ThreadID: 6 Semaphore: semaphore-2  time:11:53.8862
Start - ThreadID: 8 Semaphore: semaphore-1  time:11:53.8862
Start - ThreadID: 3 Semaphore: semaphore-2  time:11:53.8862
Start - ThreadID: 5 Semaphore: semaphore-2  time:11:53.8862
Start - ThreadID: 1 Semaphore: semaphore-1  time:11:53.8862
Start - ThreadID: 2 Semaphore: semaphore-1  time:11:53.8862
Start - ThreadID: 9 Semaphore: semaphore-2  time:11:54.8479
Released - ThreadID: 4 Semaphore: semaphore-1  time:11:54.9266
Released - ThreadID: 1 Semaphore: semaphore-1  time:11:54.9267
Released - ThreadID: 6 Semaphore: semaphore-2  time:11:54.9268
Released - ThreadID: 5 Semaphore: semaphore-2  time:11:54.9267
Released - ThreadID: 8 Semaphore: semaphore-1  time:11:55.9270
Released - ThreadID: 2 Semaphore: semaphore-1  time:11:55.9271
Released - ThreadID: 3 Semaphore: semaphore-2  time:11:55.9270
Released - ThreadID: 7 Semaphore: semaphore-2  time:11:55.9271
Released - ThreadID: 9 Semaphore: semaphore-2  time:11:56.9272

Contributing at GitHub