Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stream disposed too soon #40

Closed
MatthewSteeples opened this issue Feb 23, 2017 · 2 comments
Closed

Stream disposed too soon #40

MatthewSteeples opened this issue Feb 23, 2017 · 2 comments

Comments

@MatthewSteeples
Copy link

using (var ms = memoryStreamManager.GetStream(nameof(ZipOutputStreamHelper)))
{
    using (StreamWriter writer = new StreamWriter(ms))
    using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
    {
        var ser = new JsonSerializer();
        ser.Serialize(jsonWriter, sequence);
        jsonWriter.Flush();
    }
    return ms.ToArray();
}

We use a pattern like this in our code. Basically, the implementation of the JsonTextWriter is such that it doesn't finish off writing to the stream until it is disposed. Calling Flush doesn't seem to finalise it. This worked fine as a MemoryStream, but not as a RecycledMemoryStream. Because Streams call Dispose on their underlying Streams we end up disposing the RecycledMemoryStream before we access the array.

Is there a way to change this at all? Or is it going to be a case of finding a way to correct the behaviour of the JsonTextWriter so that we can finalise the stream before calling ToArray?

@Rattenkrieg
Copy link

Probably you should use StreamWriter constructor with leaveOpen parameter.

@MatthewSteeples
Copy link
Author

That was exactly it. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants