根据微软的样本,以下是如何通过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;
}
}
...
Run Code Online (Sandbox Code Playgroud)
现在,我怎么知道谁在转移完成后负责释放FileStream?
编辑:如果代码放在"使用"块中,流将在客户端收到任何内容之前关闭.
该服务应该清理而不是客户端.对于OperationBehaviorAttribute.AutoDisposeParameters,WCF的默认值似乎是正确的,因此它应该为您进行处理.虽然似乎没有一个固定的答案.
您可以尝试使用OperationContext.OperationCompleted事件:
OperationContext clientContext = OperationContext.Current;
clientContext.OperationCompleted += new EventHandler(delegate(object sender, EventArgs args)
{
if (fileStream != null)
fileStream.Dispose();
});
Run Code Online (Sandbox Code Playgroud)
在你回来之前把它.
查看此博客
| 归档时间: |
|
| 查看次数: |
1700 次 |
| 最近记录: |