首页 > 解决方案 > 如何在 C# 的不同线程中同步从 MemoryString 写入文件?

问题描述

我的线程使用块压缩文件。然后我需要将它保存回磁盘。代码看起来像这样:


static void WorkerCompression()
{
    using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(FilePath, FileMode.Open))
    {
        using (MemoryMappedViewStream inputStream = mmf.CreateViewStream(offset, size, MemoryMappedFileAccess.Read))
        {
            using (MemoryStream outputStream = new MemoryStream())
            {
                using (GZipStream compressionStream = new GZipStream(outputStream, CompressionMode.Compress, true))
                {
                    inputStream.CopyTo(compressionStream);
                }

                // Try to sync save in file from 'outputStream' here
            }
        }
    }
}


static void Main(string[] args)
{
    for (int i = 0; i < processors; i++)
    {
        var thread = new Thread(WorkerCompression);
        thread.Name = i.ToString();
        thread.Start();
    }

    Console.ReadLine();
}

如何将存档同步到文件?有没有办法等待信号直到第一个流完成工作,在附加文件第二个流接收信号之后,附加它等等?

标签: c#multithreading

解决方案


如果您使用线程,则必须自己创建信号。

您可以将 ManualResetEvent 传递给您的方法,并在最后发出信号。

static void WorkerCompression(ManualResetEvent finished)
{
       /* do your stuff*/
       finished.Set();
}

static void Main(string[] args)
{
    WaitHandle[] handles = new WaitHandle[processors];
    for (int i = 0; i < processors; i++)
   {
      handles[i] = new ManualResetEvent(false);
      var thread = new Thread(WorkerCompression);
      thread.Name = i.ToString();
      thread.Start(handles[i]);
   }
   WaitHandle.WaitAll(handles)
   /* here we arrive only if all is finished*/

   Console.ReadLine();
}

但是使用 Task 和使用 Task.WaitAll 的效果完全相同,而且工作量更少。

如果你想做,一件接一件的工作,不要使用线程!


推荐阅读