简体   繁体   中英

COM Object - Threading - .net

Is there any way to execute a method of a com object inside a completely new thread, not attached to the main thread? I have tried using a backgrounWorker, and even using a new thread by doing Dim thr as new Thread(AddressOf blah) and neither work. I am not referencing the COM object anywhere but inside the threaded function "blah" or the backgroundWorker's DoWork method, yet still my main UI locks up as it tries to process the COM object's methods I am calling.

I really need to make this execute the methods from the com object in a separate thread because it is causing my whole application to lock up.

Below is an example of my Thread that uses a method "DoWork". The same logic can be taken for a background worker

Public Sub Reconnect_Scanner() Implements Scanners.Reconnect_Scanner

    'Do our request on a new thread
    Dim thread As New System.Threading.Thread(AddressOf Connect)
    thread.SetApartmentState(Threading.ApartmentState.STA)
    thread.Start()


End Sub

Public Sub Connect()

    'Get a new instance of our scanner
    Dim scanner As New OposScanner_CCO.OPOSScanner

    'Loop until scanner is opened 
    Do
        Debug.Print("looking for scanner")
        'If we find the device, exit do
        Dim openId As Integer = scanner.Open("Honeywell")
        If openId = 0 Then Exit Do

        'Sleep 1 second 
        System.Threading.Thread.Sleep(250)

    Loop

End Sub

Even though that should be running on a completely new thread, once it does scanner.open my main thread locks up till it is complete.

I appreciate any help.

COM takes care of the object's threading requirements as published in the registry by the ThreadingModel registry key. Yours is obviously "Apartment", which makes COM take care of thread-safety on the object's behalf. That's very common. And yes, if you created it on the UI thread then COM marshals the call from your worker thread back to the UI thread.

To bypass that, you'd have to create a separate STA thread to give the object another thread-safe home. That requires creating a Thread, calling its SetApartmentState() method to make it STA and calling Application.Run() to run a message loop. That in itself is hard to deal with because you lose control, you'll want a Form or a Timer or Control.BeginInvoke() to generate events that let you use the object's methods. This is all pretty unpleasant, an hourglass cursor was popular in the olden days.

在辅助线程中创建COM组件,这样您的COM方法就不会被编组到Main UI线程中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM