第一次调用服务的方法也会打开通道。这被称为自动打开,不建议使用。相反,您应该显式地调用它:
channel.Open();
channel.RetrieveFoobars();
然而,问题仍然存在:channel.Open()不尊重绑定的OpenTimeout,而是在大约21秒后抛出一个EndpointNotFoundException异常。我猜这是WCF CommunicationObject的一个bug。
使用上述代码设置((IContextChannel)channel).OperationTimeout、bind.SendTimeout或bind.OpenTimeout并没有帮助(如其他地方所建议的)。
基于此VB代码
(请看这里),我找到了解决方案:使用允许您指定等待时间以在取消前使用异步方法。
private void CloseChannel(ICommunicationObject channel){
try {
channel.Close();
} catch {
channel.Abort();
}
}
private void OpenChannel(ICommunicationObject channel, TimeSpan timeout) {
var ar = channel.BeginOpen(null, null);
if (!ar.AsyncWaitHandle.WaitOne(timeout, true)) {
CloseChannel(channel);
throw new EndpointNotFoundException();
}
channel.EndOpen(ar);
}
您仍需先将绑定的OpenTimeout设置至少为50毫秒,否则BeginOpen会抛出TimeoutException。
bind.OpenTimeout = TimeSpan.FromMilliseconds(100d)
{}
)以使其格式化和语法高亮! - marc_s