Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何锁定流?_C#_Multithreading_Stream - Fatal编程技术网

C# 如何锁定流?

C# 如何锁定流?,c#,multithreading,stream,C#,Multithreading,Stream,我有两个线程: 线程1正在写入流 线程2正在从该流读取数据 在线程2中,如何锁定线程1不向其写入?这样我就可以从小溪里读到水了 MemoryStream outputStream= new MemoryStream(); 线程1: stream = System.IO.File.OpenRead(fileToSend); compressor.CompressionMethod = SevenZip.CompressionMethod.Lzma2; compressor.Compression

我有两个线程:

线程1正在写入流

线程2正在从该流读取数据

在线程2中,如何锁定线程1不向其写入?这样我就可以从小溪里读到水了

MemoryStream outputStream= new MemoryStream();
线程1:

stream = System.IO.File.OpenRead(fileToSend);
compressor.CompressionMethod = SevenZip.CompressionMethod.Lzma2;
compressor.CompressionLevel = SevenZip.CompressionLevel.Fast;

compressor.CompressStream(stream, outputStream);
我想读取线程2中的outputstream。 我尝试过使用
lock(outputStream)
outputStream.lock(0,outputStream.Lengh)
这两种方法都不会阻止线程1向其写入


我正在使用sevenZipSharp

而不是同时进行读写操作,我建议您将压缩流直接写入网络

不幸的是,我认为sevenZipSharp库不可能直接写入NetworkStream

作为替代,您可以使用。它能够直接写入NetworkStream。它已经包含在.NET Framework(System.dll)中,可以开箱即用

我已经用1MB的数据测试了上面的代码,并成功地从接收器中获得了缩小的大小(压缩)

1048576 bytes of raw-data sent.
1033 bytes of compressed-data received.
我的测试代码在这里可用


编辑:至于将其解压缩回来,您可以从
新的DeflateStream(streamReadingCompressedData,CompressionMode.Decompress)

完成对流的写入后,是否尝试关闭该流。线程1可能仍然持有句柄。我不确定在同时进行写入和读取时,此库是否足够线程安全。当你写一些东西时,不能保证在写作者关闭之前,另一个线程能够立即阅读。我建议你进行连续的写作和阅读。(写->关闭->读->关闭->等等)就是这样,我不想关闭它。压缩机大约需要30秒才能完成工作。我想,当他在做他的事情阻止他向
outputstream
写入数据时,让我从中读取。你打算获取压缩或未压缩的数据吗?嗯,这违背了目的。我不想关上它。没有代码阻止流被访问吗?因此,我不再使用SevenZipSharp了。这种压缩方法有快有慢吗?你能告诉我缺点吗?它应该更快,因为你不需要一个临时内存流来保存临时压缩数据。事实上,deflate通常用作网络中的压缩,因为它可以动态进行压缩,无需等待Close()被调用。我不确定其缺点。与其他慢速算法相比,压缩比可能不是很好。这是非常好的(如果
deflate
足够快的话)。现在我正在使用7zipSharp,将一个文件块一个块地分开,分别压缩每个块,然后发送它们。它采取了很多步骤。希望这会更快。在你的pastebin中你没有使用解压缩,对吗?
1048576 bytes of raw-data sent.
1033 bytes of compressed-data received.