Sharing a file stream async

  • Thread starter Thread starter frustrated
  • Start date Start date
F

frustrated

I am trying to share a file stream between two threads,
but havent got a clue as to how to do it.

The first thread will be reading the file, and the second
thread will(/might) be writing to the same file stream. I
was going to pass a ref to the file stream to the second
thread, but the problem comes when I am trying to read
from one section of the stream and write to another. I
dont want one thread changing the position of the stream
pointer, then have the other thread writing in that
position.

The only thing that I could find is the readerwriterlock
class, but there has got to be a slicker solution that
alows me to have two stream pointers.

Any ideas?
 
frustrated,
Have you consider letting each thread have its own FileStream object?

When you create the file stream objects, you can specify a FileShare on one
of the overloaded constructors, something like:

' thread1
Dim input As New FileStream("file.txt", FileMode.Open,
FileAccess.Read, FileShare.ReadWrite)

' thread2
Dim output As New FileStream("file.txt", FileMode.Open,
FileAccess.Write, FileShare.ReadWrite)

Using two streams will ensure the read Position won't collide with the write
Position.

To ensure that only one thread is reading or write at the same time I would
probably use SyncLock in both threads on a common "padlock" object.

Private Shared m_padlock As New Object ' YES! New object!

' thread1
SyncLock m_padlock
input.Read(...)
End Synclock

' thread2
SyncLock m_padlock
input.Write(...)
End Synclock

Hope this helps
Jay
 
Thanks Jay

One other question, if I create two seprate file streams
to read and to write the file, then wont the writen data
be buffered? The read stream wont see that data until a
flush occures. If I remember correctly, it could be up to
8k of memory being buffered. Not realy desireable for what
I am attempting to do.

Can any of the other filestream constructors be set to the
same memory buffer?

Eg.
Public Sub New( _
ByVal handle As IntPtr, _
ByVal access As FileAccess, _
ByVal ownsHandle As Boolean, _
ByVal bufferSize As Integer, _
ByVal isAsync As Boolean _
)


(Unfortunatly I have not found a good reference on
filestream information. )

Once again, thanks for the help.
 
frustrated,
Can any of the other filestream constructors be set to the
same memory buffer? No.

One other question, if I create two separate file streams
to read and to write the file, then wont the written data
be buffered?
Yes, unless you use the override to set the Buffer size to 1, effectively
turning off buffering.

I would simply call Flush after the Read or the Write.

Hope this helps
Jay
 
Back
Top