Setting a timeout on the remote WMI when the RPC server is unavailable

I have the following code that checks the status of a service on a remote computer. The problem is that if the remote computer cannot be found (he or something else), then the method ManagementObjectSearcher.Get()takes 20 seconds to give the error "RPC server is unavailable." In cases where the server is unavailable, I want to explicitly indicate that I want it to be tried for a short period of time (e.g. 3 seconds). I followed the post here , but it states that it should use the Timeout parameter for ManagementObjectSearcher, but my code seems to ignore this value (since it states that this does not apply to collections). Is there something that I am missing on these parameters? I tried using the property , but to no avail. ReturnImmediatly

public static void WmiServiceCheck()
    {
        try
        {
            var computerName = "SomeInvalidComputer";
            var serviceName = "Power";
            var managementScope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", computerName));
            var objectQuery = new ObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName));
            var searcher = new ManagementObjectSearcher(managementScope, objectQuery);
            searcher.Options.Timeout = new TimeSpan(0, 0, 0, 3); // Timeout of 3 seconds
            var managementObjectCollection = searcher.Get();
            var serviceState = managementObjectCollection.Cast<ManagementObject>().ToList().Single()["State"].ToString();
            /// Other stuff here
        }
        catch (Exception ex)
        {
        }
    }
+4
2

, . ConnectionOptions.Timeout:

  var managementScope = new ManagementScope(...);
  managementScope.Options.Timeout = TimeSpan.FromSeconds(3);

, .

, 3 , , , , . , hoppin . , . 10 , . 20 .

+8

, , . .

Dim wmiScope As New Management.ManagementScope("\\" & HOST_COMPUTER_HERE & "\root\cimv2")
Dim exception As Exception = Nothing
Dim timeRan As Integer = 0
Dim wmiThread As Threading.Thread = New Threading.Thread(Sub() Wmi_Connect(wmiScope))
    wmiThread.Start()
    While wmiThread.ThreadState = Threading.ThreadState.Running
        Threading.Thread.Sleep(1000)
        timeRan += 1000
'WmiThreadTimeout is a global variable set to 10,000 miliseconds.
            If timeRan >= WmiThreadTimeout Then
                wmiThread = Nothing
                    exception = New Exception(HostName & " could not be connected to within the timeout period.")
                End If
                Exit While
            End If
        End While

.

Private Sub Wmi_Connect(ByRef wmiScope As Management.ManagementScope)
    Try
        wmiScope.Connect()
    Catch ex As System.Runtime.InteropServices.COMException
    End Try
End Sub

, . , . ( , Thread Nothing .) ​​

+1

All Articles