/LockFile

Simplest lock file implementation

Primary LanguageC#MIT LicenseMIT

LockFile

Build Tests NuGet NuGet Donate Donate

LockFile is the simplest lock file implementation for .NET.

Download

Features

  • Dead simple
  • Targets .NET Framework 4.5+ and .NET Standard 2.0+

Usage

Lock files are acquired by opening a file with FileShare.None, which guarantees exclusive access to file. Lock files are released when they are disposed.

Try to acquire a lock file once

using (var lockFile = LockFile.TryAcquire("some.lock"))
{
    if (lockFile != null)
    {
        // Lock file acquired
    }
}

Wait until lock file is released and acquire it

using (var lockFile = LockFile.WaitAcquire("some.lock"))
{
    // Lock file is eventually acquired
}

Or you can set a timeout via CancellationToken:

using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2)))
using (var lockFile = LockFile.WaitAcquire("some.lock", cts.Token))
{
    // If lock file is not acquired within 2 seconds, an exception is thrown
}

Libraries used

Donate

If you really like my projects and want to support me, consider donating to me on Patreon or BuyMeACoffee. All donations are optional and are greatly appreciated. 🙏