• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
Download
Show / Hide Table of Contents

DistributedLock.Core API Usage

This page provides examples for acquiring and releasing distributed locks, semaphores, and reader-writer locks with NCache.

Note

This feature is currently supported in the NCache OpenSource edition.

Important

The DistributedLock.Core integration is supported in NCache OSS 5.3.6.2 and later.

Prerequisites

Before using DistributedLock.Core APIs with NCache, make sure the following prerequisites are fulfilled:

  • .NET
  • Install the following NuGet package in your .NET application:
    • OpenSource: NCache.OSS.DistributedLock
  • Include the following namespaces in your application:
    • Alachisoft.NCache.Client
    • NCache.DistributedLock.Providers
  • All application instances coordinating access to the same resource must connect to the same NCache cache and use the same synchronization primitive name.
  • The NCache cache must be configured and running.
  • NCacheDistributedSynchronizationProvider must be initialized.

Acquire a Distributed Lock

Use Acquire when the operation must obtain the lock or fail with an exception. Acquire blocks until the lock is acquired, the timeout elapses, or cancellation is requested. The returned handle must be disposed to release the lock.

The following example acquires a distributed lock for invoice processing.

IDistributedLock distributedLock = provider.CreateLock("invoice-processing");

using (IDistributedSynchronizationHandle handle = distributedLock.Acquire(
    timeout: TimeSpan.FromSeconds(10),
    cancellationToken: CancellationToken.None))
{
    // Only one application instance can execute this section at a time.
    ProcessInvoices();
}

When the using block exits, Dispose() releases the lock. If another application instance already holds the lock, this call waits until the timeout expires. If the timeout expires, Acquire throws TimeoutException. If cancellation is requested, it throws OperationCanceledException.

Note

The timeout parameter specifies how long the caller waits to acquire the lock. It does not define lock ownership expiration. Lock expiration is configured through the optional expirationTime parameter of NCacheDistributedSynchronizationProvider.

Note

The same timeout and cancellation behavior applies to semaphore and reader-writer lock acquisition methods. Acquire methods throw TimeoutException when the timeout expires, while try-acquire methods return null. Cancellation results in OperationCanceledException.

Try to Acquire a Distributed Lock

Use TryAcquire when the application should continue without an acquisition-timeout exception if the lock is unavailable. It returns null if the lock is not acquired before the timeout. Cancellation still results in OperationCanceledException.

The following example tries to acquire the same lock and exits if ownership is not available.

IDistributedLock distributedLock = provider.CreateLock("invoice-processing");

using (IDistributedSynchronizationHandle handle = distributedLock.TryAcquire(
    timeout: TimeSpan.FromSeconds(2),
    cancellationToken: CancellationToken.None))
{
    if (handle == null)
    {
        Console.WriteLine("Lock was not acquired.");
        return;
    }

    ProcessInvoices();
}

If the handle is null, the application did not acquire the lock and should not enter the protected section.

Acquire a Distributed Lock Asynchronously

Use AcquireAsync when the calling workflow is asynchronous. The returned handle should be disposed asynchronously by using await using.

The following example acquires a distributed lock asynchronously.

IDistributedLock distributedLock = provider.CreateLock("invoice-processing");

await using (IDistributedSynchronizationHandle handle = await distributedLock.AcquireAsync(
    timeout: TimeSpan.FromSeconds(10),
    cancellationToken: CancellationToken.None))
{
    await ProcessInvoicesAsync();
}

Acquire a Distributed Semaphore Slot

A semaphore allows up to maxCount concurrent holders. Use it for throttling distributed work such as background jobs, file processing, or calls to external services.

The following example acquires a semaphore slot for email sending.

IDistributedSemaphore semaphore = provider.CreateSemaphore(
    name: "email-sending",
    maxCount: 5);

using (IDistributedSynchronizationHandle handle = semaphore.Acquire(
    timeout: TimeSpan.FromSeconds(10),
    cancellationToken: CancellationToken.None))
{
    SendEmailBatch();
}

Up to five acquisitions can hold semaphore slots concurrently across all application instances. A slot is released when its handle is disposed.

Try to Acquire a Semaphore Slot

Use TryAcquire when the application should continue without an acquisition-timeout exception if a semaphore slot is unavailable. It returns null if a slot is not acquired before the timeout. Cancellation still results in OperationCanceledException.

The following example tries to acquire a semaphore slot and exits if all slots are already held.

IDistributedSemaphore semaphore = provider.CreateSemaphore(
    name: "email-sending",
    maxCount: 5);

using (vIDistributedSynchronizationHandle handle = semaphore.TryAcquire(
    timeout: TimeSpan.FromSeconds(2),
    cancellationToken: CancellationToken.None))
{
    if (handle == null)
    {
        Console.WriteLine("No semaphore slot is currently available.");
        return;
    }

    SendEmailBatch();
}

If the handle is null, no semaphore slot was acquired.

Acquire a Reader Lock

Reader locks allow multiple concurrent readers. A new reader cannot acquire the lock while a writer holds the lock or is waiting to acquire it.

The following example acquires a read lock before loading product catalog data.

IDistributedReaderWriterLock readerWriterLock = provider.CreateReaderWriterLock("product-catalog");

using (IDistributedSynchronizationHandle handle = readerWriterLock.AcquireReadLock(
    timeout: TimeSpan.FromSeconds(10),
    cancellationToken: CancellationToken.None))
{
    var products = LoadProducts();
}

The read lock is released when the handle is disposed.

Acquire a Write Lock

Write locks require exclusive ownership. If readers currently hold the lock, the writer waits for them to release it. Once a writer is waiting, new readers cannot acquire the lock until the writer's acquisition attempt completes.

The following example acquires a write lock before updating product catalog data.

IDistributedReaderWriterLock readerWriterLock = provider.CreateReaderWriterLock("product-catalog");

using (IDistributedSynchronizationHandle handle = readerWriterLock.AcquireWriteLock(
    timeout: TimeSpan.FromSeconds(10),
    cancellationToken: CancellationToken.None))
{
    UpdateProductCatalog();
}

The write lock is released when the handle is disposed.

Try to Acquire Reader and Writer Locks

Use try-acquire methods when the application should continue without an acquisition-timeout exception if reader or writer ownership is unavailable. These methods return null when ownership is not acquired before the timeout. Cancellation still results in OperationCanceledException.

The following example tries to acquire a write lock and exits if exclusive access is not available.

IDistributedReaderWriterLock readerWriterLock = provider.CreateReaderWriterLock("product-catalog");

using (IDistributedSynchronizationHandle handle = readerWriterLock.TryAcquireWriteLock(
    timeout: TimeSpan.FromSeconds(2),
    cancellationToken: CancellationToken.None))
{
    if (handle == null)
    {
        Console.WriteLine("Write lock was not acquired.");
        return;
    }

    UpdateProductCatalog();
}

The following example tries to acquire a read lock and exits if read access is not available.

IDistributedReaderWriterLock readerWriterLock = provider.CreateReaderWriterLock("product-catalog");

using (IDistributedSynchronizationHandle handle = readerWriterLock.TryAcquireReadLock(
    timeout: TimeSpan.FromSeconds(2),
    cancellationToken: CancellationToken.None))
{
    if (handle == null)
    {
        Console.WriteLine("Read lock was not acquired.");
        return;
    }

    var products = LoadProducts();
}

If the handle is null, the application did not acquire the requested reader or writer lock.

Note

Semaphores and reader-writer locks also provide asynchronous acquisition methods, including AcquireAsync, TryAcquireAsync, AcquireReadLockAsync, TryAcquireReadLockAsync, AcquireWriteLockAsync, and TryAcquireWriteLockAsync.

Release Synchronization Ownership

Locks, semaphore slots, read locks, and write locks are released by disposing the returned IDistributedSynchronizationHandle. Use Dispose() for synchronous release.

The following example releases the lock in a finally block.

IDistributedLock distributedLock = provider.CreateLock("invoice-processing");

IDistributedSynchronizationHandle handle = distributedLock.Acquire(
    timeout: TimeSpan.FromSeconds(10),
    cancellationToken: CancellationToken.None);

try
{
    ProcessInvoices();
}
finally
{
    handle.Dispose();
}

For asynchronous workflows, use await using to invoke DisposeAsync() when the asynchronous scope exits, as shown in Acquire a Distributed Lock Asynchronously.

Important

If the protected operation runs longer than the configured expiration, ownership can expire before the operation completes and another application instance may acquire the same primitive.

See Also

DistributedLock.Core with NCache
NCache as DistributedLock.Core Provider

Contact Us

PHONE

+1 214-619-2601   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top