Skip to content

Instantly share code, notes, and snippets.

@khalidsalomao
Last active May 11, 2016 15:23
Show Gist options
  • Save khalidsalomao/bcb00e64d98b4b99ccf8 to your computer and use it in GitHub Desktop.
Save khalidsalomao/bcb00e64d98b4b99ccf8 to your computer and use it in GitHub Desktop.
A simple lock mechanism using the filesystem. The lock contains a timestamp that is periodically updated, but will expire if the application dies...
#region * License *
/*
SimpleHelpers - SimpleFileLock
Copyright © 2015 Khalid Salomão
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
License: http://www.opensource.org/licenses/mit-license.php
Website: https://gist.github.com/khalidsalomao/bcb00e64d98b4b99ccf8
*/
#endregion
using System;
using System.Threading;
using System.Threading.Tasks;
namespace SimpleHelpers
{
/// <summary>
/// A simple lock mechanism using the filesystem.
/// The lock contains a timestamp that is periodically updated, but will expire if the application dies...
/// </summary>
public class SimpleFileLock
{
/// <summary>Lock max age in milliseconds before expiring.</summary>
public const int LockMaxAge = 20000;
/// <summary>Internal update rate in milliseconds to keep the lock alive.</summary>
public const int LockUpdateRate = 10000;
string padLockFileName = "padLock";
System.Threading.Timer maintenanceTask = null;
bool lockAcquired = false;
/// <summary>Name of the file. Must be a valid filename.</summary>
public string LockName
{
get { return padLockFileName; }
}
/// <summary>
/// Checks if the lock was acquired.
/// </summary>
public bool LockAcquired
{
get { return lockAcquired; }
}
/// <summary>
/// This method will be called to notify that AcquireLock was
/// unable to acquire lock and may retry if the retry count is high enough
/// </summary>
public Action<int, string> OnAcquireLockFail { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="SimpleFileLock" /> class.
/// </summary>
/// <param name="lockName">Name of the lock. Must be a valid filename.</param>
public SimpleFileLock (string lockName)
{
if (!String.IsNullOrEmpty (lockName))
padLockFileName = lockName;
}
/// <summary>
/// Tries to acquire a lock. A lock is acquired if the file is not found or is older than 20 seconds.<para/>
/// The lock will be updated every 10 seconds until Release() is called.
/// </summary>
/// <param name="retryCount">Number of retries before returning with error if lock is not acquired</param>
/// <param name="waitMilliseconds">Wait time between retries</param>
/// <returns></returns>
public bool AcquireLock (int retryCount = 3, int waitMilliseconds = 5000)
{
int tryCount = 1;
while (!TryToAcquireLock ())
{
if (OnAcquireLockFail != null)
OnAcquireLockFail (tryCount, String.Format ("Failed to acquire lock. Try count {0}/3", tryCount));
tryCount++;
if (tryCount > retryCount)
return false;
Task.Delay (waitMilliseconds).Wait ();
}
return lockAcquired;
}
bool TryToAcquireLock ()
{
DateTime padLock;
DateTime.TryParse (FileUtils.ReadFileAllText (padLockFileName).Trim (), out padLock);
if ((DateTime.UtcNow - padLock).TotalMilliseconds > LockMaxAge)
{
System.IO.File.WriteAllText (padLockFileName, DateTime.UtcNow.ToString ("o"));
lockAcquired = true;
maintenanceTask = new System.Threading.Timer (i => System.IO.File.WriteAllText (padLockFileName, DateTime.UtcNow.ToString ("o")), null, LockUpdateRate, LockUpdateRate);
return true;
}
return false;
}
/// <summary>
/// Releases the file lock.
/// </summary>
public void Release (bool forceRelease = false)
{
// remove maintenance timer
if (maintenanceTask != null)
{
maintenanceTask.Dispose ();
maintenanceTask = null;
}
if (lockAcquired || forceRelease)
{
Thread.Sleep (0);
// remove file lock
FileUtils.TryDeleteFile (padLockFileName);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment