Using TextReader to Read Bytes

In the past, I used BinaryReader to read several bytes, but lately I got this error:

An error has occurred: Probable I/O race condition detected while copying memory. The I/O package is not thread safe by default. In multithreaded applications, a stream must be accessed in a thread-safe way, such as a thread-safe wrapper returned by TextReader or TextWriter Synchronized methods. This also applies to classes like StreamWriter and StreamReader. at System.Buffer.InternalBlockCopy(Array src, Int32 srcOffset, Array dst, Int32 dstOffset, Int32 count) at System.IO.FileStream.Read(Byte[] array, Int32 offset, Int32 count) at System.IO.BinaryReader.FillBuffer(Int32 numBytes) at System.IO.BinaryReader.ReadUInt16() 

So, as a result, I decided to use synchronous TextReader methods, such as:

 public class SafeReader { private Stream m_Stream; private TextReader m_TextReader; public SafeReader(Stream stream) { m_TextReader = TextReader.Synchronized(new StreamReader(m_Stream = stream)); } public Stream BaseStream { get { return m_Stream; } } public int ReadInt32() { // this doesn't even need to do anything (just has to read 4 bytes and it gets disposed of anyway); ReadUInt16(); ReadUInt16(); return -1; } public short ReadInt16() { return (short)(this.ReadUInt16()); } public ushort ReadUInt16() { return BitConverter.ToUInt16(new byte[] { (byte)(m_TextReader.Read() & 0xFF), (byte)(m_TextReader.Read() & 0xFF) }, 0); //return (ushort)(((m_TextReader.Read() & 0xFF)) | ((m_TextReader.Read() & 0xFF) << 8)); } } 

However, the return values ​​(pretty much reads the image in native format) are incorrect. "Images" have a slight bluish tint, and I feel that this may be due to the fact that TextReader reads text (and reads encoded characters, rather than just reading byte values).

Is there a "thread safe" way, for example TextReader Synchronized () for reading binary files?

+4
source share
2 answers

You can use BinaryReader instead of TextReader . Just make sure you lock array in the thread you are accessing from it (write).

 Object locker = new Object; lock (locker) { //BinaryReader here } 

From another thread (s) use the same:

 lock (locker) { //read from array (read is thread-safe though) } 

If the write operation is performed in another thread, it will wait until the object is unlocked.

You can also use File.ReadAllBytes if you do not need to read pieces.

Alternatively, use ASCII or UTF8 encoding with Textreader.

+1
source

Try File.ReadAllBytes() . You can then use a MemoryStream to retrieve values ​​from the buffer.

+1
source

All Articles