WCF Streaming - Who Closes a File?

According to Microsoft samples, here's how to translate the WCF throuhg file:

// Service class which implements the service contract public class StreamingService : IStreamingSample { public System.IO.Stream GetStream(string data) { //this file path assumes the image is in // the Service folder and the service is executing // in service/bin string filePath = Path.Combine( System.Environment.CurrentDirectory, ".\\image.jpg"); //open the file, this could throw an exception //(eg if the file is not found) //having includeExceptionDetailInFaults="True" in config // would cause this exception to be returned to the client try { FileStream imageFile = File.OpenRead(filePath); return imageFile; } catch (IOException ex) { Console.WriteLine( String.Format("An exception was thrown while trying to open file {0}", filePath)); Console.WriteLine("Exception is: "); Console.WriteLine(ex.ToString()); throw ex; } } ... 

Now, how do I know who is responsible for releasing FileStream when the transfer is complete?

EDIT: if the code is placed inside the "using" block, the thread is disconnected before the client receives anything.

+4
source share
3 answers

The service should clean, not the client. The default WCF for OperationBehaviorAttribute.AutoDisposeParameters seems to be true, so it should do the recycling for you. Although there is no fixed answer on this.

You can try using OperationContext.OperationCompleted Event :

 OperationContext clientContext = OperationContext.Current; clientContext.OperationCompleted += new EventHandler(delegate(object sender, EventArgs args) { if (fileStream != null) fileStream.Dispose(); }); 

Put this before your return.

Mark this blog

+5
source

Short answer: calling code via using block.

Long answer: the code sample should never be delayed as an example of good practice, it is only there to illustrate one very specific concept. In real code, there would never be a try block that does not add any value to the code. Errors should be logged at the highest level, not in depth. Given this, the sample becomes the only File.OpenRead(filePath) expression that will simply be connected to the using block that requires it.

UPDATE (after viewing more code):

Just return the stream from the function, WCF will decide when to dispose of it.

0
source

The stream must be closed by the party responsible for reading it. For example, if a service returns a stream to a client, this is because the client application closes the stream because the Service does not know or has control when the client finishes reading the stream. In addition, WCF will not care to close the stream again due to the fact that it does not know when the receiving side has finished reading. :)

NTN, Amit Bhatia

0
source

Source: https://habr.com/ru/post/1446065/


All Articles