Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF Streaming - who closes the file?

Tags:

wcf

streaming

According to Microsoft's samples, here's how one would go about streaming a file throuhg WCF:

   // 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 
            //(e.g. 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's responsible for releasing the FileStream when the transfer is done?

EDIT: If the code is put inside a "using" block the stream gets shut down before the client receives anything.

like image 736
Otávio Décio Avatar asked Nov 14 '12 18:11

Otávio Décio


1 Answers

The service should clean up and not the client. WCF's default for OperationBehaviorAttribute.AutoDisposeParameters seems to be true, therefore it should do the disposing for you. Although there doesn't seem to be a fixed answer on this.

You could try using the OperationContext.OperationCompleted Event:

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

Put that before your return.

Check this blog

like image 163
Science_Fiction Avatar answered Oct 18 '22 04:10

Science_Fiction