LockFile is the simplest lock file implementation for .NET.
- NuGet:
dotnet add package LockFile
- Continuous integration
- Dead simple
- Targets .NET Framework 4.5+ and .NET Standard 2.0+
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.
using (var lockFile = LockFile.TryAcquire("some.lock"))
{
if (lockFile != null)
{
// Lock file acquired
}
}
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
}
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. ๐