简体   繁体   English

从同一个流抛出多次读取流不支持并发IO读取或写入操作

[英]Multiple read from same stream throwing Stream does not support concurrent IO read or write operations

I am downloading files.For that I divided file into segments. 我正在下载文件。为此,我将文件分为多个部分。
Each segment concurrently accessing the same Input Stream. 每个段同时访问同一输入流。 So the error Stream does not support concurrent IO read or write operations occurs in Stream.Read() Method. 因此错误Stream does not support concurrent IO read or write operations发生在Stream.Read()方法中。
My code is 我的代码是

Stream InputStream = response.GetResponseStream(); //where response is HttpWebResponse
//Following Read is called for each segment
InputStream.Read(buffer, offset, bytesToRead);

My Question is how to read from multiple thread at same time.It should be possible as many downloaders has concurrent segment download facility.Also let me know if I missing something. 我的问题是如何同时从多个线程读取数据,这应该是可能的,因为许多下载程序都具有并发的段下载功能,也请告知我是否丢失了某些内容。

You can use lock to allow single thread to read at a time. 您可以使用来允许一次读取单个线程。

Stream InputStream = null;

lock(InputStream)
{
  InputStream = response.GetResponseStream(); //where response is HttpWebResponse
  //Following Read is called for each segment
  InputStream.Read(buffer, offset, bytesToRead);
}

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock. 通过获取给定对象的互斥锁,执行一条语句然后释放该锁,lock关键字将语句块标记为关键部分。 The following example includes a lock statement, MSDN . 下面的示例包括一个锁语句MSDN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM