流作为 WCF 中的返回值 - 谁处理它?

发布于 2024-11-17 05:42:59 字数 228 浏览 0 评论 0原文

假设我有以下 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

要走干脆点 2024-11-24 05:42:59

服务负责关闭流,除非您更改默认行为它会自动执行 (始终使用具有默认值的行为)。如果将 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 to false you must register handler for OperationContext.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).

相思故 2024-11-24 05:42:59

如果您将 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.

他夏了夏天 2024-11-24 05:42:59

您可以在 WCF 中处理返回的流,如下所示

FileStream stream=null;
OperationContext clientContext = OperationContext.Current;
clientContext.OperationCompleted += (sender, args) =>
{
    if (stream != null)
        stream.Dispose();
};

stream = new FileStream(path, FileMode.Open, FileAccess.Read);
return stream;

You can dispose returned stream in WCF like below

FileStream stream=null;
OperationContext clientContext = OperationContext.Current;
clientContext.OperationCompleted += (sender, args) =>
{
    if (stream != null)
        stream.Dispose();
};

stream = new FileStream(path, FileMode.Open, FileAccess.Read);
return stream;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文