C# 为整个应用保留一个wcf客户端代理
我有高负载ASP.NETMVC2网站和该网站使用的WCF服务。早些时候,我每次需要时都创建一个代理,甚至没有关闭它。请参阅我的(非常感谢SO用户),我发现我应该关闭此代理。换句话说,它将成功 现在,我在应用程序启动时创建一个代理,然后检查它并在需要时重新创建它。下面是代码:C# 为整个应用保留一个wcf客户端代理,c#,.net,asp.net-mvc,wcf,wcf-client,C#,.net,Asp.net Mvc,Wcf,Wcf Client,我有高负载ASP.NETMVC2网站和该网站使用的WCF服务。早些时候,我每次需要时都创建一个代理,甚至没有关闭它。请参阅我的(非常感谢SO用户),我发现我应该关闭此代理。换句话说,它将成功 现在,我在应用程序启动时创建一个代理,然后检查它并在需要时重新创建它。下面是代码: public static bool IsProxyValid(MyServ.MyService client) { bool result = true; if ((client == null) || (
public static bool IsProxyValid(MyServ.MyService client) {
bool result = true;
if ((client == null) || (client.State != System.ServiceModel.CommunicationState.Opened) // || (client.InnerChannel.State != CommunicationState.Opened)
)
result = false;
return result;
}
public static AServ.AServClient GetClient(HttpContext http) {
if (!IsProxyValid((MyService)http.Application["client"]))
http.Application["client"] = new MyService();
return (MyService)http.Application["client"];
}
public static MyServ.MyService GetClient(HttpContextBase http)
{
if (!IsProxyValid((MyService)http.Application["client"]))
http.Application["client"] = new MyService();
return (MyService)http.Application["client"];
}
public ActionResult SelectDepartment(string departments)
{
try
{
MyService svc = CommonController.GetClient(this.HttpContext);
Department[] depsArray = svc.GetData(departments);
// .... I cut here ....
return View();
}
catch (Exception exc)
{
// log here
return ActionUnavailable();
}
}
你们怎么看?它应该正常工作吗?有时我的应用程序会死机。我认为这是因为客户端代理状态确定不正确,应用程序试图使用损坏的代理
后期编辑 此外,在TCP监视器中,我看到许多已建立的站点到服务的连接。为什么它创建了很多连接而不是使用一个全局连接?调用服务方法时可能发生异常,使其处于故障状态
希望你们的帮助 我认为在创建新通道之前,如果通道出现故障,您需要中止该通道,然后 确保关闭/中止旧客户机如果您创建新客户机,请为此使用类似的方法(此方法与singleton中的DI一起使用)
我认为,如果通道出现故障,您需要先中止该通道,然后再创建一个新通道 确保关闭/中止旧客户机如果您创建新客户机,请为此使用类似的方法(此方法与singleton中的DI一起使用)
好的,谢谢你的回答!我应该用
client.State
检查client.InnerChannel.State
,还是只检查client.State
?我尝试了您的解决方案,但有很多连接,而不是只有一个。我做错了什么?MyServiceClientInitializer应该是通过VisualStudio进行singletonI调试的,并查看只创建了一次的连接。但为什么它会产生这么多物理连接?InitializeClient方法只被调用一次吗?好的,谢谢你的回答!我应该用client.State
检查client.InnerChannel.State
,还是只检查client.State
?我尝试了您的解决方案,但有很多连接,而不是只有一个。我做错了什么?MyServiceClientInitializer应该是通过VisualStudio进行singletonI调试的,并查看只创建了一次的连接。但为什么它会产生这么多物理连接?InitializeClient方法只被调用一次吗?
public class MyServiceClientInitializer : IMyServiceClientInitializer
{
[ThreadStatic]
private static MyServ.MyService _client;
public MyServ.MyService Client
{
get
{
if (_client == null
|| (_client.State != CommunicationState.Opened
&& _client.State != CommunicationState.Opening))
IntializeClient();
return _client;
}
}
private void IntializeClient()
{
if (_client != null)
{
if (_client.State == CommunicationState.Faulted)
{
_client.Abort();
}
else
{
_client.Close();
}
}
string url = //get url;
var binding = new WSHttpBinding();
var address = new EndpointAddress(url);
_client = new MyServ.MyService(binding, address);
}
}