From 3e5b03ee36873fac8cf455b0f3f65ba2525d057d Mon Sep 17 00:00:00 2001 From: Simnico99 Date: Thu, 26 Jan 2023 10:19:30 -0500 Subject: [PATCH] Optimized the Further functions. --- src/ZirconNet.Core/Async/QueueAsync.cs | 61 ++++++---------- src/ZirconNet.Core/IO/FileWrapperBase.cs | 70 ++++++++----------- src/ZirconNet.Core/IO/JsonFileWrapper.cs | 4 +- .../Runtime/CustomIntEnumerator.cs | 3 +- 4 files changed, 53 insertions(+), 85 deletions(-) diff --git a/src/ZirconNet.Core/Async/QueueAsync.cs b/src/ZirconNet.Core/Async/QueueAsync.cs index 77cd9e2..44c4287 100644 --- a/src/ZirconNet.Core/Async/QueueAsync.cs +++ b/src/ZirconNet.Core/Async/QueueAsync.cs @@ -1,52 +1,43 @@ -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> _queuedActions = new List>(); - private readonly ILogger? _logger; + private readonly ConcurrentQueue> _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 actionToRun) + private async Task RunAction(Func 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); } /// @@ -54,30 +45,22 @@ private async Task RunAction(Func actionToRun) /// /// The current task to run. /// Cancellation token - /// The current running action public async Task AddTaskAsync(Func actionToRun, CancellationToken cancellationToken = default) { if (!cancellationToken.IsCancellationRequested) { - await RunAction(actionToRun); + await RunAction(actionToRun, cancellationToken); } } /// /// Wait for the current queued items to reach 0. /// - /// The current task that wait the queue to end. - /// 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); } } -} \ No newline at end of file +} diff --git a/src/ZirconNet.Core/IO/FileWrapperBase.cs b/src/ZirconNet.Core/IO/FileWrapperBase.cs index ef5eb57..fac3fff 100644 --- a/src/ZirconNet.Core/IO/FileWrapperBase.cs +++ b/src/ZirconNet.Core/IO/FileWrapperBase.cs @@ -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; @@ -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() @@ -92,7 +66,20 @@ 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; } } @@ -100,38 +87,37 @@ 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); } -} - +} \ No newline at end of file diff --git a/src/ZirconNet.Core/IO/JsonFileWrapper.cs b/src/ZirconNet.Core/IO/JsonFileWrapper.cs index d6822a6..6cc85a6 100644 --- a/src/ZirconNet.Core/IO/JsonFileWrapper.cs +++ b/src/ZirconNet.Core/IO/JsonFileWrapper.cs @@ -92,7 +92,7 @@ private async Task IsFileLockedAsync() } count++; - if (IsFileLocked(_fileInfo)) + if (IsFileLocked(_fileInfo.FullName)) { await Task.Delay(1000); } @@ -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 diff --git a/src/ZirconNet.Core/Runtime/CustomIntEnumerator.cs b/src/ZirconNet.Core/Runtime/CustomIntEnumerator.cs index 3908551..567a066 100644 --- a/src/ZirconNet.Core/Runtime/CustomIntEnumerator.cs +++ b/src/ZirconNet.Core/Runtime/CustomIntEnumerator.cs @@ -26,7 +26,6 @@ internal CustomIntEnumerator(Range range) _end = range.End.Value; } - public int Current => _current; public bool MoveNext() @@ -34,4 +33,4 @@ public bool MoveNext() _current++; return _current <= _end; } -} +} \ No newline at end of file