WCF流 - 谁关闭文件?

5
根据微软的示例,以下是如何通过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;
            }
        }
...

现在,当传输完成时,我如何知道谁负责释放FileStream?
编辑:如果将代码放入“using”块中,则在客户端接收任何内容之前,流将被关闭。
3个回答

6

服务应该清理而不是客户端。WCF的OperationBehaviorAttribute.AutoDisposeParameters的默认值似乎为true,因此它应该为您处理处置。尽管在这方面似乎没有固定的答案。

您可以尝试使用 OperationContext.OperationCompleted事件

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

在你的返回语句之前放置它。

检查这个博客


0

简短回答:通过 using 块,调用代码。

详细回答:示例代码永远不应该被视为良好实践的典范,它只是为了说明一个非常具体的概念而存在。真正的代码永远不会像那样有一个 try 块,因为它对代码没有任何价值。错误应该在最高层记录,而不是在深处。考虑到这一点,示例变成了一个单一表达式,File.OpenRead(filePath),它将被简单地插入到需要它的 using 块中。

更新(查看更多代码后):

只需从函数返回流,WCF 将决定何时处理它。


1
我不能使用“using”块,因为那会关闭流。 - Otávio Décio

0

流需要由负责读取它的一方关闭。例如,如果服务将流返回给客户端,则客户端应用程序有责任关闭流,因为服务不知道或无法控制客户端何时完成读取流。此外,由于WCF不知道接收方何时完成读取,因此WCF也不会再次负责关闭流。

希望对你有所帮助, Amit Bhatia


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接