c# - 如何在 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();
}
如何将存档同步到文件?有没有办法等待信号直到第一个流完成工作,在附加文件第二个流接收信号之后,附加它等等?
解决方案
如果您使用线程,则必须自己创建信号。
您可以将 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 的效果完全相同,而且工作量更少。
如果你想做,一件接一件的工作,不要使用线程!
推荐阅读
- ruby-on-rails - 尝试用 jest 测试反应组件时无法编译 js.erb 导入的模块
- dns - 我收到“type master”错误;在我的 named.conf 文件中
- here-api - 这里 Maps cors 问题 - 只有本地资源(没有外部资源)
- java - Android 11 运行时存储权限
- python - 为什么存储“for循环”的结果不起作用?
- c++ - 您可以在 C++ 中动态分配带有向量作为字段的类吗?
- google-cloud-platform - Google Cloud 如何对默认服务帐号进行身份验证?
- c++ - 如何在一串字符中找到一个单词,其中字符可能由空格分隔
- django - 如何从 django 视图调用 js 脚本?
- python - 人脸识别项目错误:cv2.error: error: (-215:Assertion failed) isMap() in function 'operator[]'