Stream as a return value in WCF - who disposes it?

.NetWcfStreamIdisposable

.Net Problem Overview


Let's say I have the following WCF implementation:

public Stream Download(string path)
{
    FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
    return stream;
}

Who's responsible for disposing the returned value? After all, a network failure might occur, hence the consumer might not be able to dispose it.

.Net Solutions


Solution 1 - .Net

Service is responsible for closing stream and unless you change default behavior it does it automatically (the behavior with defalut values is always used). If you set OperationBehavior.AutoDisposeParameters to false you must register handler for OperationContext.OperationCompleted and dispose the stream in the handler as described here.

Client cannot close the stream because client has a different one - you are not passing reference to your stream or reference to your file handler. Internally file content is copied to transport and client processes it in its own stream instance (where he is responsible for disposing it).

Solution 2 - .Net

If you wrap the Stream in MessageContract (so you could sent more information in headers), beware that the Stream would not be disposed automatically! As the name of attribute OperationBehavior.AutoDisposeParameters suggests, WCF automatically disposes input/output parameters and thus you have to implement IDisposable on your MessageContract class and close the stream there.

Solution 3 - .Net

You can dispose returned stream in WCF like below

FileStream stream=null;
OperationContext clientContext = OperationContext.Current;
clientContext.OperationCompleted += (sender, args) =>
{
    if (stream != null)
        stream.Dispose();
};

stream = new FileStream(path, FileMode.Open, FileAccess.Read);
return stream;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRon KleinView Question on Stackoverflow
Solution 1 - .NetLadislav MrnkaView Answer on Stackoverflow
Solution 2 - .NetPeter SladekView Answer on Stackoverflow
Solution 3 - .NetJameel MoideenView Answer on Stackoverflow