userda
userda

Reputation: 625

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.
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.

Upvotes: 2

Views: 2764

Answers (1)

Adil
Adil

Reputation: 148180

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. The following example includes a lock statement, MSDN.

Upvotes: 1

Related Questions