Skip to content

Commit

Permalink
Backport use of thread delay over sleep and handle dispose in FileSys…
Browse files Browse the repository at this point in the history
…temMainDomLock (#18151)

* Backport use of thread delay over sleep and handle dispose in FileSystemMainDomLock (from PRs #18119 and #18147)

* Applied suggestion from code review.
  • Loading branch information
AndyButland authored Feb 12, 2025
1 parent 048f8bc commit a282cc5
Showing 1 changed file with 29 additions and 10 deletions.
39 changes: 29 additions & 10 deletions src/Umbraco.Infrastructure/Runtime/FileSystemMainDomLock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ internal class FileSystemMainDomLock : IMainDomLock
private readonly string _lockFilePath;
private readonly ILogger<FileSystemMainDomLock> _logger;
private readonly string _releaseSignalFilePath;
private bool _disposed;
private Task? _listenForReleaseSignalFileTask;

private FileStream? _lockFileStream;
Expand Down Expand Up @@ -88,16 +89,14 @@ public Task ListenAsync()
ListeningLoop,
_cancellationTokenSource.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
TaskScheduler.Default)
.Unwrap(); // Because ListeningLoop is an async method, we need to use Unwrap to return the inner task.

return _listenForReleaseSignalFileTask;
}

public void Dispose()
{
_lockFileStream?.Close();
_lockFileStream = null;
}
/// <summary>Releases the resources used by this <see cref="FileSystemMainDomLock" />.</summary>
public void Dispose() => Dispose(true);

public void CreateLockReleaseSignalFile() =>
File.Open(_releaseSignalFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite,
Expand All @@ -107,7 +106,27 @@ public void CreateLockReleaseSignalFile() =>
public void DeleteLockReleaseSignalFile() =>
File.Delete(_releaseSignalFilePath);

private void ListeningLoop()
/// <summary>Releases the resources used by this <see cref="FileSystemMainDomLock" />.</summary>
/// <param name="disposing">true to release both managed resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_logger.LogInformation($"{nameof(FileSystemMainDomLock)} Disposing...");
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();
ReleaseLock();
_disposed = true;
}
}

private void ReleaseLock()
{
_lockFileStream?.Close();
_lockFileStream = null;
}

private async Task ListeningLoop()
{
while (true)
{
Expand All @@ -126,12 +145,12 @@ private void ListeningLoop()
{
_logger.LogDebug("Found lock release signal file, releasing lock on {lockFilePath}", _lockFilePath);
}
_lockFileStream?.Close();
_lockFileStream = null;

ReleaseLock();
break;
}

Thread.Sleep(_globalSettings.CurrentValue.MainDomReleaseSignalPollingInterval);
await Task.Delay(_globalSettings.CurrentValue.MainDomReleaseSignalPollingInterval, _cancellationTokenSource.Token);
}
}
}

0 comments on commit a282cc5

Please sign in to comment.