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

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 is responsible for deleting the return value? In the end, a network failure can occur, so the consumer cannot dispose of it.

+52
stream idisposable wcf
Jun 26 2018-11-11T00:
source share
3 answers

The service is responsible for closing the stream and, if you do not change the default behavior, it does this automatically (the behavior with defalut values ​​is always used). If you set OperationBehavior.AutoDisposeParameters to false , you must register a handler for OperationContext.OperationCompleted and delete the stream in the handler, as described here .

The client cannot close the stream, because the client has a different one - you do not pass a link to your stream or a link to your file handler. The internal contents of the file are copied for the transport, and the client processes it in its stream instance (where it is responsible for deleting it).

+48
Jun 26 '11 at 11:02
source share

If you exchange Stream in MessageContract (so that you can send additional information in the headers), be careful that Stream is not deleted automatically! As the OperationBehavior.AutoDisposeParameters attribute name implies, WCF automatically provides I / O parameters, and therefore you must implement IDisposable in your MessageContract class and close the stream there.

+32
Oct 19 2018-11-21T00:
source share

You can delete the returned stream in WCF as shown 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; 
+1
Nov 16 '14 at 8:51
source share



All Articles