Better Code Using Jacob and WMI

≯℡__Kan透↙ 提交于 2019-12-11 01:33:03

问题


I am using JACOB to access system information through WMI. I have not found much documentation for WMI and Jacob on the web and was wondering if I could get some help in making the code a little more efficient.

Here is the code:

ActiveXComponent mActiveXWMI = new ActiveXComponent("winmgmts:\\\\localhost\\root\\CIMV2");
String query = "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name='_Total'";
Variant vCollection = mActiveXWMI.invoke("ExecQuery", new Variant(query));

EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
Dispatch item = null;
while (enumVariant.hasMoreElements()) {
    item = enumVariant.nextElement().toDispatch();
    cpuUsage = Double.parseDouble(Dispatch.call(item, "PercentProcessorTime").toString());
}

As one can see, it doesn't seem to make much sense of looping through a collection for just one item. I would like to just query for one column in the query statement and get the result from that as quickly and efficiently as possible, with as little overhead as possible.

Does anyone have much experience with JACOB and retrieving these values in the best way possible?

Thanks,

Steve


回答1:


My understanding is that in general, WMI will always return a collection of zero or more items for any ExecQuery. And if JACOB's EnumVariant class is the best way to receive the info from WMI (from the examples I've seen), then you need to enumerate through it in one way or another.

(You might be able to compress a few more lines together, like EnumVariant enumVariant = new EnumVariant( mActiveXWMI.invoke("ExecQuery", new Variant(query)).toDispatch() );--but that makes it even harder to read, and won't help performance or anything.)

If you're certain the query will return no more than one item--as in your example--you could change the "while" to an "if" statement (and then handle the case where it fails in your "else" clause).

But otherwise... I don't think it's going to get much shorter than what you have already.



来源:https://stackoverflow.com/questions/1817459/better-code-using-jacob-and-wmi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!