简体   繁体   English

WCF客户端,是否保留引用?

[英]WCF clients, hold reference or not?

Consider the following scenario: 请考虑以下情形:

There is a windows service hosting a WCF service. 有一个Windows服务托管WCF服务。

The WCF service provides an interface between clients and an AppFabric server located on a physically different machine. WCF服务在客户端和位于物理上不同的计算机上的AppFabric服务器之间提供接口。 It retreievs objects, does calculations on it and returns the best one. 它回收对象,对其进行计算并返回最佳对象。

20-30 clients can connect to the service at the same time which is not that much. 20-30个客户端可以同时连接到该服务,这并不是很多。

What would be better, create an instance every time a query is done on the service or have the client object as a member and call functions. 最好在每次对服务进行查询时创建一个实例,或者将客户端对象作为成员并调用函数。 Creating an instance litters everything with try finally block which I dont like but what about the client connection, what are the disadvantages? 创建一个实例会使我不喜欢的try finally块杂乱无章,但是客户端连接又有什么缺点呢? Can the host be restarted and have clients still work? 主机可以重新启动并且客户端仍然可以工作吗? What is the usual/preferred way to do this? 通常/首选方式是什么?

try
{
  PreOrderService.PreorderServiceClient proxy = new   PreOrderService.PreorderServiceClient("netTcpPreorderService");

  List<PreOrder> preOrders = proxy.FindWallet(preOrder.WalletId);
}
finally
{
  if (proxy.State != CommunicationState.Faulted)
    proxy.Close();
}

I prefer to do the following: 我更喜欢执行以下操作:

proxy = newServiceReference1.ServiceDataContractTestClient(); 
try
{ 
    proxy.MetodThrowsException();
    proxy.Close(); 
} 
catch
{ 
    proxy.Abort(); 
    throw; // Or handle exception
}

This does not care if the server connection has been lost, and does not throw a CommunicationObjectFaultedException when proxy.MetodThrowsException() breaks the server. 这并不关心服务器连接是否丢失,并且proxy.MetodThrowsException()断开服务器时也不会引发CommunicationObjectFaultedException。

If you find that it reduces readability, then wrap it in a separate method. 如果发现它降低了可读性,则将其包装在单独的方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM