如何锁定流? [英] How to lock a Stream?

查看:131
本文介绍了如何锁定流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个线程:

线程1正在写入流.

线程2正在从该流中读取.

And thread 2 is reading from that stream.

我如何在线程2中锁定线程1使其无法写入?这样我就可以从信息流中读取该信息了?

How can i, in thread 2, lock the thread 1 from writing to it? So that i can read the from the stream?

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对其进行写入.

I want to read from the outputstream in the thread 2. I have tried using lock(outputStream) and outputStream.Lock(0,outputStream.Lengh) and both don't stop thread 1 from writing to it.

我正在使用sevenZipSharp

推荐答案

而不是阅读&同时写入时,建议您将压缩后的流直接写入网络.

Rather than doing reading & writing simultaneously, I advise you to write the compressed stream directly to the network.

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

Unfortunately, I don't think it's possible for sevenZipSharp library to write directly into NetworkStream.

或者,您可以使用 DeflateStream 代替.它可以直接写入NetworkStream.它已经包含在.NET Framework(System.dll)中.

As alternative, you can use DeflateStream instead. It's able to write to NetworkStream directly. It's already included out-of-the-box within .NET Framework (System.dll).

client.Connect(targetHost, port);
var networkStreamRaw = client.GetStream();
var networkStreamCompressed = new DeflateStream(networkStreamRaw, CompressionMode.Compress);
{
    networkStreamCompressed.Write(rawData, 0, rawData.Length);
}

我已经用1MB的数据测试了上面的代码,并成功地从接收器中获取了压缩后的尺寸.

I have tested the code above with 1MB of data, and successfully get reduced-size (compressed) from the receiver.

1048576 bytes of raw-data sent.
1033 bytes of compressed-data received.

可在此处找到我的测试代码 http://pastebin.com/X0SYjYD7

My test code is available here http://pastebin.com/X0SYjYD7

至于将其解压缩,您可以从new DeflateStream(streamReadingCompressedData, CompressionMode.Decompress)中获得.

as for decompressing it back, you can get that from new DeflateStream(streamReadingCompressedData, CompressionMode.Decompress).

这篇关于如何锁定流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆