流作为 WCF 中的返回值 - 谁处理它?
假设我有以下 WCF 实现:
public Stream Download(string path)
{
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
return stream;
}
谁负责处理返回值?毕竟,可能会出现网络故障,因此消费者可能无法处理它。
Let's say I have the following WCF implementation:
public Stream Download(string path)
{
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
return stream;
}
Who's responsible for disposing the returned value? After all, a network failure might occur, hence the consumer might not be able to dispose it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
服务负责关闭流,除非您更改默认行为它会自动执行 (始终使用具有默认值的行为)。如果将
OperationBehavior.AutoDisposeParameters
设置为false
,则必须为OperationContext.OperationCompleted
注册处理程序,并按所述处理处理程序中的流此处。客户端无法关闭流,因为客户端有不同的流 - 您没有传递对流的引用或对文件处理程序的引用。内部文件内容被复制到传输,客户端在其自己的流实例中处理它(他负责处理它)。
Service is responsible for closing stream and unless you change default behavior it does it automatically (the behavior with defalut values is always used). If you set
OperationBehavior.AutoDisposeParameters
tofalse
you must register handler forOperationContext.OperationCompleted
and dispose the stream in the handler as described here.Client cannot close the stream because client has a different one - you are not passing reference to your stream or reference to your file handler. Internally file content is copied to transport and client processes it in its own stream instance (where he is responsible for disposing it).
如果您将 Stream 包装在 MessageContract 中(这样您就可以在标头中发送更多信息),请注意 Stream 不会自动释放!正如属性 OperationBehavior.AutoDisposeParameters 的名称所示,WCF 自动处理输入/输出参数,因此您必须在 MessageContract 类上实现 IDisposable 并在那里关闭流。
If you wrap the Stream in MessageContract (so you could sent more information in headers), beware that the Stream would not be disposed automatically! As the name of attribute OperationBehavior.AutoDisposeParameters suggests, WCF automatically disposes input/output parameters and thus you have to implement IDisposable on your MessageContract class and close the stream there.
您可以在 WCF 中处理返回的流,如下所示
You can dispose returned stream in WCF like below