gpt4 book ai didi

WCF Streaming - 谁关闭文件?

转载 作者:行者123 更新时间:2023-12-04 18:46:25 26 4
gpt4 key购买 nike

根据 Microsoft 的示例,以下是通过 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?

编辑:如果将代码放在“使用”块中,则在客户端收到任何内容之前,流将关闭。

最佳答案

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

您可以尝试使用 OperationContext.OperationCompleted Event :

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

把它放在你回来之前。

检查这个 blog

关于WCF Streaming - 谁关闭文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13384886/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com