Skip to content

Commit

Permalink
Optimized the Further functions.
Browse files Browse the repository at this point in the history
  • Loading branch information
Simnico99 committed Jan 26, 2023
1 parent 1c5348e commit 3e5b03e
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 85 deletions.
61 changes: 22 additions & 39 deletions src/ZirconNet.Core/Async/QueueAsync.cs
Original file line number Diff line number Diff line change
@@ -1,83 +1,66 @@
using Microsoft.Extensions.Logging;
using ZirconNet.Core.Extensions;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

namespace ZirconNet.Core.Async;

public sealed class QueueAsync
{
private readonly SemaphoreSlim _semaphoreSlim;
private readonly SemaphoreSlim _lockSemaphore = new(1, 1);
private readonly IList<Func<Task>> _queuedActions = new List<Func<Task>>();
private readonly ILogger? _logger;
private readonly ConcurrentQueue<Func<Task>> _queuedActions = new();

public QueueAsync(int maximumThreads = -1, ILogger? logger = null)
public QueueAsync(int maximumThreads = -1)
{
if (maximumThreads <= 0)
{
maximumThreads = Environment.ProcessorCount;
}

_semaphoreSlim = new(maximumThreads);
_logger = logger;
_semaphoreSlim = new SemaphoreSlim(maximumThreads);
}

private async Task RunAction(Func<Task> actionToRun)
private async Task RunAction(Func<Task> actionToRun, CancellationToken cancellationToken)
{
if (_queuedActions.CountThreadSafe() == 0)
{
await _lockSemaphore.WaitAsync();
}

_queuedActions.AddThreadSafe(actionToRun);
await _semaphoreSlim.WaitAsync();
_queuedActions.Enqueue(actionToRun);
await _semaphoreSlim.WaitAsync(cancellationToken);

_ = Task.Run(async () =>
{
try
{
await actionToRun.Invoke();
}
finally
if (!cancellationToken.IsCancellationRequested)
{
_ = _semaphoreSlim.Release();
_queuedActions.RemoveThreadSafe(actionToRun);

if (_queuedActions.CountThreadSafe() == 0)
try
{
await actionToRun.Invoke();
}
finally
{
_ = _lockSemaphore.Release();
_semaphoreSlim.Release();
}
}
});
}, cancellationToken);
}

/// <summary>
/// Add a task to the running queue.
/// </summary>
/// <param name="actionToRun">The current task to run.</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>The current running action</returns>
public async Task AddTaskAsync(Func<Task> actionToRun, CancellationToken cancellationToken = default)
{
if (!cancellationToken.IsCancellationRequested)
{
await RunAction(actionToRun);
await RunAction(actionToRun, cancellationToken);
}
}

/// <summary>
/// Wait for the current queued items to reach 0.
/// </summary>
/// <returns>The current task that wait the queue to end.</returns>
/// <exception cref="SemaphoreFullException"></exception>
public async Task WaitForQueueEnd()
{
try
{
await _lockSemaphore.WaitAsync();
_ = _lockSemaphore.Release();
}
catch (SemaphoreFullException e)
while (_queuedActions.TryPeek(out _))
{
_logger?.LogWarning(e, "Error when waiting for semaphoreslim to end");
await Task.Delay(10);
}
}
}
}
70 changes: 28 additions & 42 deletions src/ZirconNet.Core/IO/FileWrapperBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
#endif
public abstract class FileWrapperBase : FileSystemInfo, IFileWrapperBase
{
protected FileInfo _fileInfo;
protected readonly FileInfo _fileInfo;
public override string FullName => _fileInfo.FullName;
public override string Name => _fileInfo.Name;
public override bool Exists => _fileInfo.Exists;
Expand Down Expand Up @@ -36,49 +36,23 @@ private static FileInfo Create(string path, bool overwrite = false)
return fileInfo;
}

private static void Copy(string inputFilePath, string outputFilePath)
public static void Copy(string inputFilePath, string outputFilePath)
{
const int bufferSize = 1024 * 1024;

using FileStream fileStream = new(outputFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
using FileStream fs = new(inputFilePath, FileMode.Open, FileAccess.ReadWrite);
fileStream.SetLength(fs.Length);
int bytesRead;
var bytes = new byte[bufferSize];

while ((bytesRead = fs.Read(bytes, 0, bufferSize)) > 0)
{
fileStream.Write(bytes, 0, bytesRead);
}
File.Copy(inputFilePath, outputFilePath, true);
}

public async Task CopyToDirectoryAsync(IDirectoryWrapperBase directory)
{
FileInfo finalPath = new(directory.FullName + @$"\{Name}");
Delete(finalPath);
while (IsFileLocked(_fileInfo))
while (IsFileLocked(_fileInfo.FullName))
{
if (IsFileLocked(_fileInfo))
if (IsFileLocked(_fileInfo.FullName))
{
await Task.Delay(250);
}
}

Copy(FullName, finalPath.FullName);
}

protected static bool IsFileLocked(FileInfo file)
{
try
{
using var stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
stream.Close();
}
catch (IOException)
{
return true;
}
return false;
File.Move(_fileInfo.FullName, finalPath.FullName);
}

public byte[] GetByteArray()
Expand All @@ -92,46 +66,58 @@ private static void Delete(FileInfo file)
{
if (file.Exists)
{
file.Delete();
File.Delete(file.FullName);
}
}

public static bool IsFileLocked(string path)
{
try
{
using (File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None)) { }
return false;
}
catch (IOException)
{
return true;
}
}

public override void Delete()
{
if (Exists)
{
_fileInfo.Delete();
File.Delete(_fileInfo.FullName);
}
}

public StreamWriter AppendText()
{
return _fileInfo.AppendText();
return File.AppendText(_fileInfo.FullName);
}

public StreamWriter CreateText()
{
return _fileInfo.CreateText();
return File.CreateText(_fileInfo.FullName);
}

public StreamReader OpenText()
{
return _fileInfo.OpenText();
return File.OpenText(_fileInfo.FullName);
}

public FileStream Open(FileMode fileMode, FileAccess access = default, FileShare share = default)
{
return _fileInfo.Open(fileMode, access, share);
return File.Open(_fileInfo.FullName, fileMode, access, share);
}

public FileStream OpenRead()
{
return _fileInfo.OpenRead();
return File.OpenRead(_fileInfo.FullName);
}

public FileStream OpenWrite()
{
return _fileInfo.OpenWrite();
return File.OpenWrite(_fileInfo.FullName);
}
}

}
4 changes: 2 additions & 2 deletions src/ZirconNet.Core/IO/JsonFileWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ private async Task<bool> IsFileLockedAsync()
}
count++;

if (IsFileLocked(_fileInfo))
if (IsFileLocked(_fileInfo.FullName))
{
await Task.Delay(1000);
}
Expand Down Expand Up @@ -131,7 +131,7 @@ await _asyncLock.Lock(async () =>

public void LoadFile(bool forceRead = false)
{
if ((_fileContent == null || forceRead) && !IsFileLocked(_fileInfo))
if ((_fileContent == null || forceRead) && !IsFileLocked(_fileInfo.FullName))
{
using StreamReader r = new(FullName);
try
Expand Down
3 changes: 1 addition & 2 deletions src/ZirconNet.Core/Runtime/CustomIntEnumerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,11 @@ internal CustomIntEnumerator(Range range)
_end = range.End.Value;
}


public int Current => _current;

public bool MoveNext()
{
_current++;
return _current <= _end;
}
}
}

0 comments on commit 3e5b03e

Please sign in to comment.