I have a custom formatter to support my web calls, but a bug report shed some light on an issue. I was overriding the WriteToStreamAsync()
method as such:
public override Task WriteToStreamAsync(Type type,
object value,
Stream writeStream,
HttpContent content,
TransportContext transportContext)
{
return Task.Run(() =>
{
if (value == null) return;
using (var sw = new StreamWriter(writeStream))
{
var serialized = _serializer.Serialize(value);
sw.Write(serialized);
}
});
}
According to this post, the issue was that the using
statement was causing the stream to close. The solution was to remove the using
statement and use an explicit Flush()
call, but it feels wrong to depend on the GC to dispose of the StreamWriter
.
public override Task WriteToStreamAsync(Type type,
object value,
Stream writeStream,
HttpContent content,
TransportContext transportContext)
{
return Task.Run(() =>
{
if (value == null) return;
var sw = new StreamWriter(writeStream);
var serialized = _serializer.Serialize(value);
sw.Write(serialized);
sw.Flush();
});
}
- Is this a major concern?
- Is there a better (more "best practice") way of doing this?