使用Jacob和WMI更好的代码 [英] Better Code Using Jacob and WMI

查看:102
本文介绍了使用Jacob和WMI更好的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JACOB通过WMI访问系统信息.我在网上找不到太多有关WMI和Jacob的文档,并且想知道我是否可以在使代码更有效的方面获得帮助.

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.

这是代码:

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.

是否有人在使用JACOB方面有丰富的经验,并以最佳方式检索这些值?

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

谢谢

史蒂夫

推荐答案

我的理解是,一般而言,WMI对于任何ExecQuery总是会返回零个或多个项目的集合.而且,如果JACOB的EnumVariant类是从WMI接收信息的最佳方式(从我看过的示例中),那么您需要以一种或另一种方式枚举它.

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.

(您可能能够将更多的行压缩在一起,例如EnumVariant enumVariant = new EnumVariant( mActiveXWMI.invoke("ExecQuery", new Variant(query)).toDispatch() );,但这会使阅读更加困难,并且对性能没有任何帮助.)

(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.)

如果您确定查询将返回不多于一项的内容(例如您的示例),则可以将"while"更改为"if"语句(然后处理如果它在您的"else"子句中失败).

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.

这篇关于使用Jacob和WMI更好的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆