如何确保你不会得到WCF Faulted状态exception?

我得到这个例外:

通信对象System.ServiceModel.Channels.ServiceChannel不能用于通信,因为它处于Faulted状态。

WCF服务使用默认的wsHttpBinding。 无论我在哪里使用WCF,我都以如下方式使用WCF:

using (var proxy = new CAGDashboardServiceClient()) { proxy.Open(); var result = proxy.GetSiteForRegion(ddlRegions.SelectedValue); ddlSites.DataSource = result; ddlSites.DataBind(); proxy.Close(); } 

消息中显示的错误行似乎是在最后一个proxy.close之后。 不知道发生了什么事。 我从Visual Studio 08内启动服务。

这里是跟踪信息:

 The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state. Server stack trace: at System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan timeout) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout) at System.ServiceModel.ClientBase`1.System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout) at System.ServiceModel.ClientBase`1.Close() at System.ServiceModel.ClientBase`1.System.IDisposable.Dispose() at CAGDashboard.UserControls.ucVolunteerCRUDGrid.ddlRegions_SelectedIndexChanged(Object sender, EventArgs e) in C:\Documents and Settings\rballalx\My Documents\Visual Studio 2008\Projects\DashboardCAG\CAGDashboard\UserControls\ucVolunteerCRUDGrid.ascx.cs:line 81 at System.Web.UI.WebControls.ListControl.OnSelectedIndexChanged(EventArgs e) at System.Web.UI.WebControls.DropDownList.RaisePostDataChangedEvent() at System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent() at System.Web.UI.Page.RaiseChangedEvents() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) 

您应该避免将客户端代理放在using块中。


更新

这个链接的答案描述了使用C#语法完成同样事情的更简单,更简洁的方法。


原帖

这是微软推荐的处理WCF客户端调用的方式:

有关更多详细信息,请参阅: 预期的例外

 try { ... double result = client.Add(value1, value2); ... client.Close(); } catch (TimeoutException exception) { Console.WriteLine("Got {0}", exception.GetType()); client.Abort(); } catch (CommunicationException exception) { Console.WriteLine("Got {0}", exception.GetType()); client.Abort(); } 

附加信息

很多人似乎都在WCF上问这个问题,微软甚至还创build了一个专门的示例来演示如何处理exception:

C:\ WF_WCF_Samples \ WCF \基本\客户端\ ExpectedExceptions \ CS \客户端

下载示例: C#或VB

考虑到涉及使用声明的问题太多了 (激烈?)在这个问题上的内部讨论和线索 ,我不会浪费时间试图成为一个牛仔代码,find一个更干净的方式。 我只是把它吸了起来,并为我的服务器应用程序实现WCF客户端这种冗长(但可信)的方式。

如果传输模式是缓冲,那么确保MaxReceivedMessageSizeMaxBufferSize的值是相同的 。 经过几个小时的努力,我才解决了故障状态问题,并认为如果有人帮助,我会在这里发布。

使用OperationContract属性标记零方法也可能导致此错误。 这是我的问题,当build立一个新的服务,并进行长期的testing。

与Ryan Rodemoyer的回答类似,我发现当合同上的UriTemplate无效时,可以得到这个错误。 在我的情况下,我使用了相同的参数两次。 例如:

 /Root/{Name}/{Name}