The property which controls the behavior of closing or not closing the parameter is the OperationBehaviorAttribute.AutoDisposeParameters
property and can be used to deviate from the default behavior of true with regards to the Stream
parameter being closed once it exits the method. This is the reason you do not often times see the explicit closing of the parameter. If you want to override default behavior, you can take explicit control and close the Stream once the operation has completed via the OperationCompleted event.
public Stream GetFile(string path) {
Sream fileStream = null;
try
{
fileStream = File.OpenRead(path);
}
catch(Exception)
{
return null;
}
OperationContext clientContext = OperationContext.Current;
clientContext.OperationCompleted += new EventHandler(delegate(object sender, EventArgs args)
{
if (fileStream != null)
fileStream.Dispose();
});
return fileStream;
}
Keep in mind that you are receiving your own copy of the Stream
, not a reference to the clients Stream
and thus you are responsible for closing it.