[英]Is it possible for a WCF channel to fault right after checking the state (single thread)?
I have been handing the closing and aborting of channels this way: 我一直以这种方式处理通道的关闭和中止:
public async Task<MyDataContract> GetDataFromService()
{
IClientChannel channel = null;
try
{
IMyContract contract = factory.CreateChannel(address);
MyDataContract returnValue = await player.GetMyDataAsync();
channel = (IClientChannel);
return returnValue;
}
catch (CommunicationException)
{
// ex handling code
}
finally
{
if (channel != null)
{
if (channel.State == CommunicationState.Faulted)
{
channel.Abort();
}
else
{
channel.Close();
}
}
}
}
Assume only a single thread uses the channel. 假设只有一个线程使用该通道。 How do we know the channel will not fault right after checking the state?
检查状态后,我们怎么知道通道不会出错? If such a thing were to happen, the code would try to Close() and Close() will throw an exception in the finally block.
如果发生这样的事情,代码将尝试Close()和Close()将在finally块中抛出异常。 An explanation about why this is safe/unsafe and examples of a better, safer way would be appreciated.
关于为什么这是安全/不安全的解释以及更好,更安全的方式的例子将不胜感激。
Yes, the state is a "snapshot" of the current state when you get it. 是的,当你得到状态时,状态是当前状态的“快照”。 In the time between when you access the CommunicationState and when you go to make a logical decision based on it, the state can have easily changed.
在您访问CommunicationState和基于它做出逻辑决策之间的时间内,状态可以很容易地改变。 A better WCF pattern is:
更好的WCF模式是:
try
{
// Open connection
proxy.Open();
// Do your work with the open connection here...
}
finally
{
try
{
proxy.Close();
}
catch
{
// Close failed
proxy.Abort();
}
}
In this way you don't rely on the state in order to make decisions. 通过这种方式,您不必依赖状态来做出决策。 You try to do the most likely thing (a healthy close) and if that fails (which it will when the CommunicationState is Faulted), you call Abort to ensure proper cleanup.
你试图做最可能的事情(一个健康的关闭),如果失败(当CommunicationState出现故障时),你可以调用Abort以确保正确清理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.