vb.net - 使用 ManagementObjectSearcher 时检测到 DisconnectedContext

标签 vb.net multithreading wmi

我在 WndProc 覆盖中使用以下函数:

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") Then
                    Return "COM" & comPortNumber
                End If
            End If
        Next
    Catch ex As Exception
    End Try

    Return ""
End Function

该函数工作正常,但我现在通过表单在新应用程序中使用它。在 For 循环的每次迭代中(在 For Each port As System... 行上),我收到以下消息:

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.

我认为这是某种线程问题。如何从表单调用此函数而不发生此错误?

<小时/>

我找到了a post on MSDN outlining a very similar problem problem 。那家伙说:

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.

我希望我能找出 Forms 应用程序中的不同之处。

<小时/>

编辑和可能的解决方案:基于DisconnectedContext MDA when calling WMI functions in single-threaded application处的答案我认为这里的解决方案是在 WndProc 之外调用 GetPortName()。今晚我将对此进行测试并发布我的结果。

最佳答案

阅读 DisconnectedContext MDA when calling WMI functions in single-threaded application 的答案后看来我的代码不起作用的原因是它是从 WndProc 调用的,阻塞了 WndProc。这会导致问题,因为编码需要泵送消息......但我已经阻止了。

就我的目的而言,只需扫描计时器就可以了。您可能必须寻找其他解决方案,例如在另一个线程上异步调用它。

关于vb.net - 使用 ManagementObjectSearcher 时检测到 DisconnectedContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5657310/

相关文章:

.net - VB.NET DLL "ActiveX component can' t 创建对象”

.net - 从 IQueryable 到 TableQuery

mysql - 大公司的Access或者MySQL

java - Asynctask 中多线程意外停止

java - 多次运行一个线程

c# - 我如何放入异常捕获

wpf - 具有自定义排序的 CollectionViewSource

c# - 如何在 Windows Phone 上运行并行任务?

c# - 无法使用 WMI 和 C# 远程终止进程

python - Python 中的共享文件夹 session