NTDLS.Semaphore 3.2.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package NTDLS.Semaphore --version 3.2.0                
NuGet\Install-Package NTDLS.Semaphore -Version 3.2.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NTDLS.Semaphore" Version="3.2.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add NTDLS.Semaphore --version 3.2.0                
#r "nuget: NTDLS.Semaphore, 3.2.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install NTDLS.Semaphore as a Cake Addin
#addin nuget:?package=NTDLS.Semaphore&version=3.2.0

// Install NTDLS.Semaphore as a Cake Tool
#tool nuget:?package=NTDLS.Semaphore&version=3.2.0                

NTDLS.Semaphore

📦 Be sure to check out the NuGet pacakge: https://www.nuget.org/packages/NTDLS.Semaphore

Pessimistic Resource

Provides various classes to protect a variable from parallel / non-sequential thread access by always acquiring an exclusive lock on the resource.

PessimisticResource using inline execution example:

An example using a PessimisticResource to envelope a variable and protect it from parallel execution, Note that there are nullable and nonnullable counterparts and also template/generics of each method to allow you to return various types from the delegate execution.

public class Car
{
    public string? Name { get; set; }
    public int NumerOhWheels { get; set; }
}

public PessimisticResource<List<Car>> Cars { get; set; } = new();

public void Add(Car car)
{
    Cars.Use((obj) => obj.Add(car));
}

public Car? GetByName(string name)
{
    return Cars.Use((obj) => obj.Where(o=>o.Name == name).FirstOrDefault());
}

public bool TryAdd(Car car)
{
    //Since TryUse<T> can return values, we have to pass the result of the try out though a variable.
    Cars.TryUse(out bool wasLockObtained, (obj) => obj.Add(car));
    return wasLockObtained;
}

public bool TryAdd(Car car, int timeout)
{
    //Since TryUse<T> can return values, we have to pass the result of the try out though a variable.
    Cars.TryUse(out bool wasLockObtained, timeout, (obj) => obj.Add(car));
    return wasLockObtained;
}

Multi PessimisticResource using inline execution example:

An example using a PessimisticResource to envelope a variable and protect it and others from parallel execution.

public class Car
{
    public string? Name { get; set; }
    public int NumerOhWheels { get; set; }
}

public PessimisticResource<List<Car>> Cars { get; set; } = new();
public CriticalSection OtherLock1 { get; set; } = new();
public CriticalSection OtherLock2 { get; set; } = new();
public CriticalSection OtherLock3 { get; set; } = new();

public void Add(Car car)
{
    Cars.Use((obj) => obj.Add(car));
}

public Car? GetByName(string name)
{
    return Cars.Use((obj) => obj.Where(o => o.Name == name).FirstOrDefault());
}

public bool TryAdd(Car car)
{
    //Since TryUse<T> can return values, we have to pass the result of the try out though a variable.
    Cars.TryUse(out bool wasLockObtained, (obj) => obj.Add(car));
    return wasLockObtained;
}

public bool TryAdd(Car car, int timeout)
{
    //Since TryUse<T> can return values, we have to pass the result of the try out though a variable.
    Cars.TryUse(out bool wasLockObtained, timeout, (obj) => obj.Add(car));
    return wasLockObtained;
}

public Car? TryGet(string name, int timeout)
{
    return Cars.TryUseAll(new[] { OtherLock1, OtherLock2, OtherLock3 }, timeout, out bool wasLockObtained, (obj) =>
    {
        //We only get here if we are able to lock "Cars" and OtherLock1, OtherLock2 and OtherLock3
        return obj.Where(o => o.Name == name).FirstOrDefault();
    });
}

Optimistic Resource

Protects a variable from parallel / non-sequential thread access but controls read-only and exclusive access separately to prevent read operations from blocking other read operations.it is up to the developer to determine when each lock type is appropriate. Note: read-only locks only indicate intention, the resource will not disallow modification of the resource, but this will lead to race conditions.

OptimisticResource using inline execution example:

An example using a CriticalSection to protect a portion of code from parallel execution while not allowing reads to block reads.

public class Car
{
    public string? Name { get; set; }
    public int NumerOhWheels { get; set; }
}

public OptimisticResource<List<Car>> Cars { get; set; } = new();

public void Add(Car car)
{
    Cars.Write((obj) => obj.Add(car));
}

public Car? GetByName(string name)
{
    return Cars.Read((obj) => obj.Where(o=>o.Name == name).FirstOrDefault());
}

public bool TryAdd(Car car)
{
    //Since TryUse<T> can return values, we have to pass the result of the try out though a variable.
    Cars.TryWrite(out bool wasLockObtained, (obj) => obj.Add(car));
    return wasLockObtained;
}

public bool TryAdd(Car car, int timeout)
{
    //Since TryUse<T> can return values, we have to pass the result of the try out though a variable.
    Cars.TryWrite(out bool wasLockObtained, timeout, (obj) => obj.Add(car));
    return wasLockObtained;
}

Critical Section

Protects an area of code from parallel / non-sequential thread access.

CriticalSection using inline execution example:

An example using a CriticalSection to protect a portion of code from parallel execution.

private CriticalSection _criticalSection = new();

private int _value;

public int Value
{
    get
    {
        return _criticalSection.Use(() => _value);
    }
    set
    {
        _criticalSection.Use(() => _value = value);
    }
}

Thread ownership tracking

If you need to keep track of which thread owns each semaphore and/or critical sections then you can enable "ThreadOwnershipTracking" by calling ThreadOwnershipTracking.Enable(). Once this is enabled, it is enabled for the life of the application so this is only for debugging deadlock/race-condition tracking. You can evaluate the ownership by evaluating the dictonary "ThreadOwnershipTracking.LockRegistration" or and instance of "PessimisticCriticalSection" or "PessimisticResource" CurrentOwnerThread.

Enabling Thread Ownership Tracking

An example of enabling the thread ownerhsip mechanism.

ThreadOwnershipTracking.Enable();

License

Apache-2.0

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net6.0

    • No dependencies.
  • net7.0

    • No dependencies.
  • net8.0

    • No dependencies.

NuGet packages (5)

Showing the top 5 NuGet packages that depend on NTDLS.Semaphore:

Package Downloads
NTDLS.ReliableMessaging

Simple, fast, secure and lightweight event or convention-based RPC implementation.

NTDLS.DelegateThreadPooling

Very high-performance active thread pool where work items can be queued as delegate functions. Allows you to easily enqueue infinite FIFO worker items or enforce queue size, wait on collections of those items to complete, and total control over the pool size. Also allows for multiple pools, so that different workloads do not interfere with one another.

NTDLS.FastMemoryCache

Provides fast and easy to use thread-safe partitioned memory cache for .net that helps manage the maximum size and track performance.

NTDLS.StreamFraming

Stream wrapper (typically TCPIP/NetworkStream) that enables reliable framing, compression, optional encryption, two-way communication, and support for query/reply. Messages are guaranteed to be received in their entirety and in the order which they were sent.

NTDLS.DatagramMessaging

Set of classes and extensions methods that allow you to send/receive UDP packets with ease. It handles corruption checks, concatenation, fragmentation, serialization and adds compression.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
3.4.2 879 8/25/2024
3.4.1 194 8/24/2024
3.4.0 111 8/24/2024
3.3.3 282 8/13/2024
3.3.2 587 7/31/2024
3.3.1 479 6/20/2024
3.3.0 2,429 1/22/2024
3.2.0 90 1/22/2024
3.1.1 223 1/4/2024
3.1.0 347 11/16/2023
3.0.0 93 11/15/2023
2.2.5 319 11/15/2023
2.2.4 137 11/14/2023
2.2.3 114 11/14/2023
2.2.2 305 11/9/2023
2.2.1 83 11/9/2023
2.2.0 123 11/9/2023
2.1.0 103 11/9/2023
2.0.0 104 11/9/2023
1.5.2 98 11/9/2023
1.5.1 366 10/17/2023
1.5.0 212 10/12/2023
1.4.0 130 10/12/2023
1.3.2 174 10/10/2023

Renamed semaphore classes to resource.