public class StateReader { ManagementObjectSearcher searcher; public StateReader() { ManagementScope scope = new ManagementScope("\\\\localhost\\root\\cimv2"); ObjectQuery query = new ObjectQuery("select Name,PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor where not Name='_Total'"); searcher = new ManagementObjectSearcher(scope,query); } // give the maximum load over all cores public UInt64 cpuLoad() { List<UInt64> list = new List<UInt64>(); ManagementObjectCollection results = searcher.Get(); foreach (ManagementObject result in results) { list.Add((UInt64)result.Properties["PercentProcessorTime"].Value); } return list.Max(); } }
使用反应式扩展更新gui:
var gui = new GUI(); var reader = new StateReader(); var sub = Observable.Interval(TimeSpan.FromSeconds(0.5)) .Select(_ => reader.cpuLoad()) .ObserveOn(gui) .Subscribe(gui.ShowcpuState); Application.Run(gui); sub.dispose();
RaceOnRCWCleanup was detected. An attempt has been mad to free an RCW that is in use. The RCW is use on the active thread or another thread. Attempting to free an in-use RCW can cause corruption or data loss.
如果我没有读取cpu负载,但只提供一些随机值,则不会出现此错误,因此错误以某种方式连接到读取负载.此外,如果我在Application.Run(gui)之后放置一个断点并在那里稍等一下,那么错误似乎并不常见.
从这个和我的谷歌搜索我认为使用管理命名空间中的类创建一个后台线程,引用包含在运行时可调用包装器中的COM对象,当我退出我的应用程序时,该线程没有时间正确关闭RCW,导致我的错误.这是正确的,我该如何解决这个问题?
我编辑了我的代码以反映我的反应,但我仍然得到同样的错误.代码更新了三点:
> StateReader是disposable,将其ManagementObjectSearcher置于dispose方法中
我在main方法中的Application.Run之后调用StateReader对象上的dispose
>在cpuLoad中,我处理了ManagementCollection和每个ManagementObject
>在我的main方法中,我在FormClosing上的事件处理程序中处理订阅对象
在gui上.这应该确保gui关闭后不会生成任何事件.
现在,在StateReader中代码的相关部分:
// give the maximum load over all cores public UInt64 cpuLoad() { List<UInt64> list = new List<UInt64>(); using (ManagementObjectCollection results = searcher.Get()) { foreach (ManagementObject result in results) { list.Add((UInt64)result.Properties["PercentProcessorTime"].Value); result.dispose(); } } return list.Max(); } public void dispose() { searcher.dispose(); }
在我的主要:
gui.FormClosing += (a1,a2) => sub.dispose(); Application.Run(gui); reader.dispose();
还有什么我可以做的,以避免我得到的错误?
解决方法
I think that using the classes in the management namespace creates a background thread that references a COM object wrapped in a Runtime Callable Wrapper
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。