本文介绍了静态对象会收集垃圾吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 如果我在一个类中声明静态对象,他们会不会收集垃圾?该类由作为Windows服务运行的WCF服务访问。那些是COM对象。类不是静态的,而是对象。使用这些对象的方法是在此类中定义的非静态方法。 命名空间 AGVController.BL { public class AGV { private static CHILKATSOCKETLib.ChilkatSocketClass objEle = new CHILKATSOCKETLib.ChilkatSocketClass(); private static CHILKATSOCKETLib.ChilkatSocketClass objGas = new CHILKATSOCKETLib.ChilkatSocketClass(); private static CHILKATSOCKETLib.ChilkatSocketClass objHeatpump = new CHILKATSOCKETLib.ChilkatSocketClass(); private static CHILKATSOCKETLib.ChilkatSocketClass objSolar = new CHILKATSOCKETLib.ChilkatSocketClass(); /// 其他方法 protected string TalkToAGVActiveXElectric( string lineCode, string IP, int port, int 模式, string 消息,字符串行, bool isPollingForAGV) { string result = ; 尝试 { if (mode == 1 ) { RegisterAGVRecord( SENT ,消息,行, false ); if (objEle!= null ) / / 在此处使用静态对象 { result = objEle.IsConnected == 1 ? ON: OFF; if (result == ON ) { int lnSuccess = objEle.SendString(message); if (lnSuccess!= 1 ) { .. ... ..... } } 解决方案 从不作为obj没有实现IDisposable。 如果你的意思是什么时候obj会收集垃圾,那么答案仍然永远不会 - 静态字段永远不会被垃圾收集,所以obj引用的对象如果将obj设置为null(或其他某个对象)并且没有对该对象的其他引用,则只有资格进行垃圾回收: obj = null; If I declare static object inside a class will they ever get garbage collected ? The class is accessed by a WCF service running as a windows service. Those are COM objects. Class is not static but objects are. Methods that are consuming those objects are non static methods defined inside this class.namespace AGVController.BL{ public class AGV { private static CHILKATSOCKETLib.ChilkatSocketClass objEle = new CHILKATSOCKETLib.ChilkatSocketClass(); private static CHILKATSOCKETLib.ChilkatSocketClass objGas = new CHILKATSOCKETLib.ChilkatSocketClass(); private static CHILKATSOCKETLib.ChilkatSocketClass objHeatpump = new CHILKATSOCKETLib.ChilkatSocketClass(); private static CHILKATSOCKETLib.ChilkatSocketClass objSolar = new CHILKATSOCKETLib.ChilkatSocketClass();///Other methods protected string TalkToAGVActiveXElectric(string lineCode, string IP, int port, int mode, string message, string line,bool isPollingForAGV) { string result = ""; try { if (mode == 1) { RegisterAGVRecord("SENT", message, line, false); if (objEle != null) // using static object here { result = objEle.IsConnected == 1 ? "ON" : "OFF"; if (result == "ON") { int lnSuccess = objEle.SendString(message); if (lnSuccess != 1) {..........}} 解决方案 Never, as obj does not implement IDisposable.If you mean when will obj get garbage collected then the answer is still never - static fields are never garbage collected and so the object that obj references will only become eligible for garbage collection if you set obj to be null (or some other object) and have no other references to that object:obj = null; 这篇关于静态对象会收集垃圾吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-01 02:06