首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用TextReader读取字节

使用TextReader读取字节
EN

Stack Overflow用户
提问于 2012-12-19 04:40:17
回答 2查看 5.6K关注 0票数 4

在过去,我一直使用BinaryReader来读取几个字节,但是最近,我得到了以下错误:

代码语言:javascript
复制
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's or TextWriter's 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()

因此,我决定使用TextReader的同步方法,如下所示:

代码语言:javascript
复制
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));
    }
}

但是,返回的值(它基本上是以专有格式读取图像)是不正确的。“图像”有一种略带蓝色的色彩,我觉得这可能是因为TextReader读取文本(并且使用编码读取字符,而不仅仅是读取字节值)。

是否有像TextReader的同步()这样的“线程安全”方式来读取二进制文件?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-19 04:44:09

您应该能够使用BinaryReader而不是TextReader。只需确保您从(编写)访问线程上的数组( lock )。

代码语言:javascript
复制
Object locker = new Object;

lock (locker) {
    //BinaryReader here
}

从其他线程中使用相同的:

代码语言:javascript
复制
lock (locker) {
    //read from array (read is thread-safe though)
}

如果存在写操作,则另一个线程将等待对象被解锁。

如果不需要以块形式阅读,也可以使用File.ReadAllBytes

或者,将ASCII或UTF8编码与T极值器一起使用。

票数 1
EN

Stack Overflow用户

发布于 2012-12-19 04:43:19

试试File.ReadAllBytes()。然后可以使用MemoryStream从缓冲区中提取值。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13945601

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档