我有一个带有方法的服务接口,该方法有一个Stream类型的参数。我应该在从流中读取所有数据后关闭流,还是在方法调用完成时由WCF运行时完成?
在我见过的大多数示例中,只从流中读取数据,而不在流上调用Close或Dispose。
通常我会说我不必关闭流,因为类不是流的所有者,但原因是为什么会问这个问题是,我们目前正在调查我们的系统中的一个问题,一些安卓客户端,使用HTTP-Post发送数据到这个服务有时有打开的连接,而不是关闭(用netstat分析,它列出了已建立的Tcp连接)。
[ServiceContract]
public interface IStreamedService {
[OperationContract]
[WebInvoke]
Stream PullMessage(Stream incomingStream);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, UseSynchronizationContext = false)]
public class MyService : IStreamedService {
public System.IO.Stream PullMessage(System.IO.Stream incomingStream) {
// using(incomingStream) {
// Read data from stream
// }
Stream outgoingStream = // assigned by omitted code;
return outgoingStream;
}服务/绑定的配置
<webHttpBinding>
<binding name="WebHttpBindingConfiguration"
transferMode="Streamed"
maxReceivedMessageSize="1048576"
receiveTimeout="00:10:00"
sendTimeout="00:10:00"
closeTimeout="00:10:00"/>
</webHttpBinding>发布于 2012-12-21 06:12:40
控制关闭或不关闭参数的行为的属性是OperationBehaviorAttribute.AutoDisposeParameters属性,一旦Stream参数退出该方法,该属性可用于偏离关闭的默认行为true。这就是为什么您不经常看到参数显式关闭的原因。如果要重写默认行为,可以通过OperationCompleted事件进行显式控制和close the Stream once the operation has completed。
public Stream GetFile(string path) {
Sream fileStream = null;
try
{
fileStream = File.OpenRead(path);
}
catch(Exception)
{
return null;
}
OperationContext clientContext = OperationContext.Current;
clientContext.OperationCompleted += new EventHandler(delegate(object sender, EventArgs args)
{
if (fileStream != null)
fileStream.Dispose();
});
return fileStream;
}请记住,您收到的是您自己的Stream副本,而不是对客户端Stream的引用,因此您有责任关闭它。
https://stackoverflow.com/questions/13952076
复制相似问题