我在ASP.NET MVC应用程序中使用WCF,并且我的每个方法都包含try-catch-finally块。我想知道我是否正在关闭/中止WCF调用。 我知道“using”语句不适合WCF调用。
以下是样本metod
public int GetInvalidOrdersCount()
{
OrderServiceClient svc = new OrderServiceClient();
try
{
return svc.GetInvalidOrdersCount();
}
catch (Exception)
{
svc.Abort();
throw;
}
finally
{
svc.Close();
}
}
答案 0 :(得分:1)
在msdn上,它显示了一个“正确”调用方式的示例:
CalculatorClient wcfClient = new CalculatorClient();
try
{
Console.WriteLine(wcfClient.Add(4, 6));
wcfClient.Close();
}
catch (TimeoutException timeout)
{
// Handle the timeout exception.
wcfClient.Abort();
}
catch (CommunicationException commException)
{
// Handle the communication exception.
wcfClient.Abort();
}
我在实施客户时通常会遵循这种模式。除此之外,您可能还希望为客户端部署using
:
using (CalculatorClient wcfClient = new CalculatorClient())
{
try
{
return wcfClient.Add(4, 6);
}
catch (TimeoutException timeout)
{
// Handle the timeout exception.
wcfClient.Abort();
}
catch (CommunicationException commException)
{
// Handle the communication exception.
wcfClient.Abort();
}
}
答案 1 :(得分:1)
我使用下面的WcfUsingWrapper
之类的东西,然后包装我的所有代理实例
void Foo(){
var client = new WcfClientType();
var result = ExecuteClient(client, x => x.WcfMethod());
}
public static ReturnType ExecuteClient<ReturnType>(ClientType client, Func<ClientType, ReturnType> webServiceMethodReference)
where ClientType : ICommunicationObject
{
bool success = false;
try
{
ReturnType result = webServiceMethodReference(client);
client.Close();
success = true;
return result;
}
finally
{
if (!success)
{
client.Abort();
}
}
}
答案 2 :(得分:0)
你要做的一件事就是检查&#34;状态&#34;连接。如果通道处于故障状态,则需要在关闭之前调用Abort()方法,否则通道将在一段时间内保持故障。如果通道没有出现故障,只需调用Close()即可。然后将其设置为null。
这样的事情:
if (requestChannel != null) {
if (requestChannel.State == System.ServiceModel.CommunicationState.Opened) {
requestChannel.Close();
requestChannel = null;
}
if (requestChannel.State == System.ServiceModel.CommunicationState.Faulted) {
requestChannel.Abort();
requestChannel.Close();
requestChannel = null;
}
}