DisconnectedContext was detected when using ManagementObjectSearcher
I am using the following function within a WndProc override:
Public Function GetPortName() As String
Dim portNameData As String
Dim comPortNumber As String
Try
Dim portSearcher As New ManagementObjectSearcher("\root\CIMV2", "Select Name, PNPDeviceID from Win32_PnPEntity")
For Each port As System.Management.ManagementObject In portSearcher.Get()
If port("Name").ToString.ToUpper.Contains("(COM") Then
portNameData = port("Name").ToString
comPortNumber = port("Name").ToString.Substring(port("Name").ToString.IndexOf("(COM") + 4)
comPortNumber = comPortNumber.TrimEnd(")"c)
If port("PNPDeviceID").ToString.ToUpper.StartsWith("USB\VID_1234&PID_1234") T开发者_Go百科hen
Return "COM" & comPortNumber
End If
End If
Next
Catch ex As Exception
End Try
Return ""
End Function
The function works fine, but I am using it in a new application now from a form. On each iteration of the For loop (on the For Each port As System...
line), I get this message:
DisconnectedContext was detected
Context 0x607fd8 is disconnected. No proxy will be used to service the request on the COM component. This may cause corruption or data loss. To avoid this problem, please ensure that all contexts/apartments stay alive until the application is completely done with the RuntimeCallableWrappers that represent COM components that live inside them.
I think this is a threading issue of some sort. How can I call this function from a form in such a way that this error doesn't occur?
I found a post on MSDN outlining a very similar problem problem. The guy says:
Sorry, don't waste your time. The code works fine when it's run in a simple console app. The problem arose when it was called in a Windows form responding to a DriveDetectorEvent.
I wish I could figure out what is different in a Forms application.
Edit and Possible Solution: Based on the answer at DisconnectedContext MDA when calling WMI functions in single-threaded application I think the solution here is to call GetPortName()
outside of WndProc. I will test this tonight and post my result.
After reading the answer at DisconnectedContext MDA when calling WMI functions in single-threaded application it seems that the reason my code doesn't work is that it is being called from WndProc, blocking WndProc. This causes problems, as marshaling requires pumping messages... but I have blocked.
For my purposes, simply scanning on a timer works. You may have to find another solution, such as calling it asynchronously on another thread.
精彩评论