"using" inside the method can cause data corruption or access issues?

I have a task that installs data in FIFO, then another thread reads that data inside FIFO one by one and sends it over the network later. The data converted to an array of bytes upon invocation FIFO.Addis as follows:

public byte[] ByteArraySerialize()
{
    using (MemoryStream m = new MemoryStream())
    {
        using (BinaryWriter writer = new BinaryWriter(m))
        {
            writer.Write((int)this.Opcode);
            writer.Write(this.Data);
        }
        return m.ToArray();
    }
}

My question is: Is it possible that the data will be corrupted or deleted before the sender stream reads it from FIFO? My question is to understand the method usinginside: How can I use the method usinginside the method can cause the GC to delete MemoryStreambefore the stream reads the data, say, a few seconds or minutes after entering this data in FIFO?

+4
4

, , :

"" , GC , , , , FIFO?

. . .ToArray(), . GC , . , GC, , .ToArray(), . , , , , GC .

, : - ?

, , .

BinaryWriter , . , MemoryStream .

:

public byte[] ByteArraySerialize()
{
    using (MemoryStream m = new MemoryStream())
    {
        using (BinaryWriter writer = new BinaryWriter(m))
        {
            writer.Write((int)this.Opcode);
            writer.Write(this.Data);
        }

        // m is really disposed here
        return m.ToArray();
    }
}

? . . , . , .NET, .

, . :

using (MemoryStream m = new MemoryStream())
using (BinaryWriter writer = new BinaryWriter(m))
{
    writer.Write((int)this.Opcode);
    writer.Write(this.Data);

    writer.Flush();
    return m.ToArray();
}

, , .

, :

using (MemoryStream m = new MemoryStream())
{
    using (BinaryWriter writer = new BinaryWriter(m, Encoding.UTF8, true))
    {
        writer.Write((int)this.Opcode);
        writer.Write(this.Data);
    }

    // m is no longer disposed here
    return m.ToArray();
}
+6

ToArray(); , .
, -, MemStreams, .

, "" , GC .
.

, :

 return m.GetBuffer();

MemStream. m Disposed, , , .

+5

, : " ". , , byte [], .

writer.Flush(); writer.Write(this.Data);.

+1

, . .

You're talking about the GC, but the idea with operators usingand IDisposableis that any resource will be released immediately when the subject is beyond the scope. We do not have to wait for GC. In other words, this has nothing to do with the GC.

0
source

All Articles