WCF:StackoverFlowexception

我在尝试servageize .NET ServiceController类时遇到exception。 当它为null时序列化很好但是一旦我填充它我得到一个stackoverflowexception。

这样可行:

[DataMember] public ServiceController MyServiceController { get { return null; } } 

但是这会给出错误“System.ServiceProcess.dll中发生类型’System.StackOverflowException’的未处理exception”:

 public class TestClass { private ServiceController _serviceController; [DataMember] public ServiceController MyServiceController { get { return ServiceController.GetServices()[0]; } } 

奇怪的是,日志中根本没有错误。 当出现错误时我可以在日志中看到它,所以不是因为我的日志不能正常工作。 这是我的配置文件

                                               

这是我的服务界面

 [ServiceContract] public interface IRdbmsService { [OperationContract] TestClass GetServiceControllerList(); } 

实施是:

  public TestClass GetServiceControllerList() { return new TestClass(); } 

有任何想法吗?

您导致序列化程序递归:

 public class TestClass { private ServiceController _serviceController; [DataMember] public ServiceController MyServiceController { get { return ServiceController.GetServices()[0]; // <-- this returns your service } } 

返回的服务是IRdbmsService ,它返回TestClass 。 然后需要序列化等。

编辑:澄清:

当序列化TestClass时,序列化程序会查看其所有DataMember属性,其中一个属性是ServiceController 。 然后它序列化这个属性,在get上执行此操作:

 return ServiceController.GetServices()[0]; 

由于IRdbmsService是作用域中定义的唯一服务,因此它位于GetServices调用响应的索引0处,因此必须进行序列化。 由于GetServiceControllerList的返回类型是TestClass ,因此必须序列化TestClass ,这将我们带回到开头(因此,递归)。

至于如何解决这个问题,这取决于你想要做什么。 此服务目前正在做的是将自己的信息返回给调用者,这对我来说没有意义; 呼叫者在消费时已经有这些信息(在打电话之前)。 你能澄清你的意图吗?

是的,在ServiceController CLASS的构造函数中,你可能会调用一些没有条件停止的递归函数,因此每次调用递归函数时,程序都会推送到堆栈,正如我所说没有停止条件,它将添加到堆栈,直到内存爆炸,因此它给出了这个错误名称StackOverFlow。

建议:添加一个断点来调试其调用递归的位置。 调试时很容易。