Search code examples
c#asp.netmemorystream

Returning a "Using" var


I need to return a MemoryStream, and currently I do it like this:

String ICallbackEventHandler.GetCallbackResult()
{

    using (var stream = new MemoryStream())
    {
        this._synth.Rate = this.Rate;
        this._synth.Volume = this.Volume;
        this._synth.SetOutputToWaveStream(stream);

        string sText = this.Context.Items["data"].ToString();
        this._synth.Speak(sText);

        //rewind to beginning of stream
        stream.Seek(0, SeekOrigin.Begin);

        using (var nMp3Stream = new MemoryStream())
        using (var rdr = new WaveFileReader(stream))
        using (var wtr = new LameMP3FileWriter(nMp3Stream, rdr.WaveFormat, LAMEPreset.STANDARD))
        {
            rdr.CopyTo(wtr);
            nMp3Stream.Position = 0;

            return (String.Concat("data:audio/mpeg;base64,", Convert.ToBase64String(nMp3Stream.ToArray())));
        }
    }
}

But I don't think that's the proper way. I guess I shouldn't return a using variable, right?

If not, how could I do this? I need to dispose the MemoryStream, I think. When should I do this, or should I let the GC do this?


Solution

  • I guess I shouldn't return a using variable, right?

    You don't return "using var" at all. You convert content of it into the string , and return that string instead.

    return (String.Concat("data:audio/mpeg;base64,", 
                       Convert.ToBase64String(nMp3Stream.ToArray())));
    

    Here you create a new instance of a string, fill it with content of MemoryStream and return that instance.

    I need to dispose the MemoryStream, I think.

    Yes, you have to think about lifetime of your instances.

    When should I do this, or should I let the GC do this?

    In most scenarios it's you who have take care of it and you're doing it proper way, at least judging from the code sample provided.

    But, a lot depends on your concrete application design and execution dynamics. For example:

    • consider performance implication of converting memory stream into the string
    • consider that at the moment of conversion you allocate almost 2x memory: one for MemoryStream another for string