Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

c# - How to set a timeout on WMI queries?

I have a .NET application which runs WMI queries on all domain computers in order to find the logged in user; it pings each computer to find whether it is online or not, then runs the actual query.

Code snippet:

try
{
    string loggedonuser = null;

    string computername = "ComputerToQuery";

    ConnectionOptions co = new ConnectionOptions();

    co.Username = "DOMAINMyUser";
    co.Password = "MyPassword";

    co.Impersonation = ImpersonationLevel.Impersonate;
    co.Authentication = AuthenticationLevel.Default;

    ManagementPath mp = new ManagementPath(@"" + computername + @"
ootcimv2");

    ManagementScope ms = new ManagementScope(mp,co);

    ms.Connect();

    ObjectQuery oq = new ObjectQuery("SELECT username FROM Win32_ComputerSystem");

    ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);

    foreach(ManagementObject mo in mos.Get())
        loggedonuser = (String) mo["username"];
}
catch(Exception e)
{
    // Handle WMI exception
}

The problem: sometimes the WMI query hangs on indefinitely.

How can I set a timeout on it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The ManagementObjectSearcher has an Options property: one of the available options is Timeout, of type TimeSpan:

Gets or sets the time-out to apply to the operation. Note that for operations that return collections, this time-out applies to the enumeration through the resulting collection, not the operation itself (the ReturnImmediately property is used for the latter). This property is used to indicate that the operation should be performed semi-synchronously.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...