Место общения программистов C#
Anonymous
ManualResetEventSlim.Wait () блокирует все задачи, начатые с задачи.run
Сообщение
Anonymous » 07 май 2025, 11:44
Я пытаюсь создать свою собственную защиту OutofmemoryException. Как только ManualResetEventSlim.Wait () достигается, приложение прекращается прогрессировать, даже если блокировка не пуста. Здесь вы можете скачать мой полный пример.
Код: Выделить всё
private readonly BlockingCollection m_fileQueue = new BlockingCollection();
private readonly Process m_currentProcess = Process.GetCurrentProcess();
static ManualResetEventSlim ManualResetEventSlim { get; set; } = new ManualResetEventSlim(false);
private const long MemoryThresholdLimit = 100L * 1024 * 1024;
private async void button1_Click(object sender, EventArgs e)
{
string readPath = @"C:\projects";
string savePath = @"C:\thrash";
List tasks = new List
{
ReadFromHddAsync(readPath),
SaveToHddAsync(savePath)
};
await Task.WhenAll(tasks);
MessageBox.Show("Done");
}
< /code>
Производитель: < /p>
private Task ReadFromHddAsync(string path)
{
return Task.Run(() => ReadFromHdd(path));
}
private void ReadFromHdd(string path)
{
foreach (var fileName in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
{
try
{
if (File.Exists(fileName))
{
var byteArray = File.ReadAllBytes(fileName);
DisposableFileBuffer disposableFileBuffer = new DisposableFileBuffer(byteArray);
m_fileQueue.Add(disposableFileBuffer);
try
{
long currentMemory = Process.GetCurrentProcess().WorkingSet64;
if (currentMemory > MemoryThresholdLimit && DisposableFileBuffer.NumberOfProcessedItemsInQueue > 0)
{
Debug.WriteLine(
$"Wait: currentMemory: {currentMemory / 1024 / 1024}Mb, DisposableFileBuffer.NumberOfProcessedItemsInQueue: {DisposableFileBuffer.NumberOfProcessedItemsInQueue}, m_fileQueue: {m_fileQueue.Count}");
ManualResetEventSlim.Reset();
ManualResetEventSlim.Wait();
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error: {ex.Message}");
}
}
}
catch (Exception ex)
{
long currentMemory = Process.GetCurrentProcess().WorkingSet64;
Debug.WriteLine($"Error: {ex.Message}, currentMemory: {currentMemory / 1024 / 1024}Mb");
}
}
}
< /code>
Consumer: < /p>
private Task SaveToHddAsync(string path)
{
return Task.Run(() => SaveToHdd(path));
}
private void SaveToHdd(string path)
{
try
{
foreach (var disposableFileBuffer in m_fileQueue.GetConsumingEnumerable())
{
string fileName = Path.Combine(path, Guid.NewGuid() + ".bin");
File.WriteAllBytes(fileName, disposableFileBuffer.Data);
try
{
disposableFileBuffer.Dispose();
long currentMemory = Process.GetCurrentProcess().WorkingSet64;
if ((MemoryThresholdLimit > currentMemory || DisposableFileBuffer.NumberOfProcessedItemsInQueue == 0) &&
!ManualResetEventSlim.IsSet)
{
Debug.WriteLine(
$"Set: currentMemory: {currentMemory / 1024 / 1024}Mb, DisposableFileBuffer.NumberOfProcessedItemsInQueue: {DisposableFileBuffer.NumberOfProcessedItemsInQueue}, m_fileQueue: {m_fileQueue.Count}");
ManualResetEventSlim.Set();
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error: {ex.Message}");
}
}
}
catch (Exception eex)
{
Debug.WriteLine($"Error: {eex.Message}");
}
}
< /code>
Helper Class, который отслеживает количество файлов, которые были взяты из блокировки, но еще не были сохранены в HDD.public class DisposableFileBuffer : IDisposable
{
public static int NumberOfProcessedItemsInQueue = 0;
public byte[] Data { get; set; }
private bool m_disposed;
public DisposableFileBuffer(byte[] data)
{
Data = data;
Interlocked.Increment(ref NumberOfProcessedItemsInQueue);
}
public void Dispose()
{
lock (this)
{
if (m_disposed) return;
Data = null;
Interlocked.Decrement(ref NumberOfProcessedItemsInQueue);
m_disposed = true;
GC.SuppressFinalize(this);
}
}
~DisposableFileBuffer()
{
Dispose();
}
}
может кто -нибудь мне помочь?
Подробнее здесь:
https://stackoverflow.com/questions/796 ... h-task-run
1746607458
Anonymous
Я пытаюсь создать свою собственную защиту OutofmemoryException. Как только ManualResetEventSlim.Wait () достигается, приложение прекращается прогрессировать, даже если блокировка не пуста. Здесь вы можете скачать мой полный пример.[code] private readonly BlockingCollection m_fileQueue = new BlockingCollection(); private readonly Process m_currentProcess = Process.GetCurrentProcess(); static ManualResetEventSlim ManualResetEventSlim { get; set; } = new ManualResetEventSlim(false); private const long MemoryThresholdLimit = 100L * 1024 * 1024; private async void button1_Click(object sender, EventArgs e) { string readPath = @"C:\projects"; string savePath = @"C:\thrash"; List tasks = new List { ReadFromHddAsync(readPath), SaveToHddAsync(savePath) }; await Task.WhenAll(tasks); MessageBox.Show("Done"); } < /code> Производитель: < /p> private Task ReadFromHddAsync(string path) { return Task.Run(() => ReadFromHdd(path)); } private void ReadFromHdd(string path) { foreach (var fileName in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories)) { try { if (File.Exists(fileName)) { var byteArray = File.ReadAllBytes(fileName); DisposableFileBuffer disposableFileBuffer = new DisposableFileBuffer(byteArray); m_fileQueue.Add(disposableFileBuffer); try { long currentMemory = Process.GetCurrentProcess().WorkingSet64; if (currentMemory > MemoryThresholdLimit && DisposableFileBuffer.NumberOfProcessedItemsInQueue > 0) { Debug.WriteLine( $"Wait: currentMemory: {currentMemory / 1024 / 1024}Mb, DisposableFileBuffer.NumberOfProcessedItemsInQueue: {DisposableFileBuffer.NumberOfProcessedItemsInQueue}, m_fileQueue: {m_fileQueue.Count}"); ManualResetEventSlim.Reset(); ManualResetEventSlim.Wait(); } } catch (Exception ex) { Debug.WriteLine($"Error: {ex.Message}"); } } } catch (Exception ex) { long currentMemory = Process.GetCurrentProcess().WorkingSet64; Debug.WriteLine($"Error: {ex.Message}, currentMemory: {currentMemory / 1024 / 1024}Mb"); } } } < /code> Consumer: < /p> private Task SaveToHddAsync(string path) { return Task.Run(() => SaveToHdd(path)); } private void SaveToHdd(string path) { try { foreach (var disposableFileBuffer in m_fileQueue.GetConsumingEnumerable()) { string fileName = Path.Combine(path, Guid.NewGuid() + ".bin"); File.WriteAllBytes(fileName, disposableFileBuffer.Data); try { disposableFileBuffer.Dispose(); long currentMemory = Process.GetCurrentProcess().WorkingSet64; if ((MemoryThresholdLimit > currentMemory || DisposableFileBuffer.NumberOfProcessedItemsInQueue == 0) && !ManualResetEventSlim.IsSet) { Debug.WriteLine( $"Set: currentMemory: {currentMemory / 1024 / 1024}Mb, DisposableFileBuffer.NumberOfProcessedItemsInQueue: {DisposableFileBuffer.NumberOfProcessedItemsInQueue}, m_fileQueue: {m_fileQueue.Count}"); ManualResetEventSlim.Set(); } } catch (Exception ex) { Debug.WriteLine($"Error: {ex.Message}"); } } } catch (Exception eex) { Debug.WriteLine($"Error: {eex.Message}"); } } < /code> Helper Class, который отслеживает количество файлов, которые были взяты из блокировки, но еще не были сохранены в HDD.public class DisposableFileBuffer : IDisposable { public static int NumberOfProcessedItemsInQueue = 0; public byte[] Data { get; set; } private bool m_disposed; public DisposableFileBuffer(byte[] data) { Data = data; Interlocked.Increment(ref NumberOfProcessedItemsInQueue); } public void Dispose() { lock (this) { if (m_disposed) return; Data = null; Interlocked.Decrement(ref NumberOfProcessedItemsInQueue); m_disposed = true; GC.SuppressFinalize(this); } } ~DisposableFileBuffer() { Dispose(); } } [/code] может кто -нибудь мне помочь? Подробнее здесь: [url]https://stackoverflow.com/questions/79609144/manualreseteventslim-wait-blocks-all-tasks-started-with-task-run[/url]
ManualResetEventSlim.Wait () блокирует все задачи, начатые с задачи.run
Anonymous »
06 май 2025, 19:55 » в форуме
C#
Я пытаюсь создать свою собственную защиту OutofmemoryException. Как только ManualResetEventSlim.Wait () достигнуто, приложение прекращается прогрессировать, даже если блокировка не пуста. PrettyPrint-Override > private readonly BlockingCollection...
0 Ответы
5 Просмотры
Последнее сообщение Anonymous
06 май 2025, 19:55
ManualResetEventSlim.Wait () блокирует все задачи, начатые с задачи.run
Anonymous »
06 май 2025, 22:38 » в форуме
C#
Я пытаюсь создать свою собственную защиту OutofmemoryException. Как только ManualResetEventSlim.Wait () достигается, приложение прекращается прогрессировать, даже если блокировка не пуста. Здесь вы можете скачать мой полный пример. private readonly...
0 Ответы
6 Просмотры
Последнее сообщение Anonymous
06 май 2025, 22:38
Std::latch C++20 latch.wait() блокирует всю программу
Anonymous »
05 янв 2024, 14:41 » в форуме
C++
Я изучаю C++20 и пытаюсь практиковать std::latch
но мой пример работает не очень хорошо. Не могли бы вы помочь мне отладить этот код?
Моя программа блокируется при вызове функции taskDone.wait()
#include #include #include #include используя...
0 Ответы
24 Просмотры
Последнее сообщение Anonymous
05 янв 2024, 14:41
Std::latch C++20 latch.wait() блокирует всю программу
Anonymous »
05 янв 2024, 15:25 » в форуме
C++
Я изучаю C++20 и пытаюсь практиковать std::latch
но мой пример работает не очень хорошо. Не могли бы вы помочь мне отладить этот код?
Моя программа блокируется при вызове функции taskDone.wait()
#include #include #include #include используя...
0 Ответы
24 Просмотры
Последнее сообщение Anonymous
05 янв 2024, 15:25
0 Ответы
6 Просмотры
Последнее сообщение Anonymous
15 фев 2025, 03:37