ManualResetEventSlim.Wait () блокирует все задачи, начатые с задачи.runC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 ManualResetEventSlim.Wait () блокирует все задачи, начатые с задачи.run

Сообщение Anonymous »

Я пытаюсь создать свою собственную защиту 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
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • ManualResetEventSlim.Wait () блокирует все задачи, начатые с задачи.run
    Anonymous » » в форуме C#
    0 Ответы
    5 Просмотры
    Последнее сообщение Anonymous
  • ManualResetEventSlim.Wait () блокирует все задачи, начатые с задачи.run
    Anonymous » » в форуме C#
    0 Ответы
    6 Просмотры
    Последнее сообщение Anonymous
  • Std::latch C++20 latch.wait() блокирует всю программу
    Anonymous » » в форуме C++
    0 Ответы
    24 Просмотры
    Последнее сообщение Anonymous
  • Std::latch C++20 latch.wait() блокирует всю программу
    Anonymous » » в форуме C++
    0 Ответы
    24 Просмотры
    Последнее сообщение Anonymous
  • Нужна помощь: сеансы пересылки портов, начатые AWS SDK, не работают и не заканчиваются менее чем за 30 секунд, почему?
    Anonymous » » в форуме C#
    0 Ответы
    6 Просмотры
    Последнее сообщение Anonymous

Вернуться в «C#»