How to lock a Stream?

2019-04-16 08:41发布

I have 2 threads:

Thread 1 is writing to a stream.

And thread 2 is reading from that stream.

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();

Thread 1:

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

compressor.CompressStream(stream, outputStream);

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.

i am using sevenZipSharp

1条回答
欢心
2楼-- · 2019-04-16 09:42

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

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

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);
}

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.

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

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

查看更多
登录 后发表回答