How to pass an ADO recordset (or any COM object) across thread boundaries?

I have an ADO Recordset object created in a background thread:

 var conn: TADOConnection; rs: _Recordset; begin conn := CreateDatabaseConnection(); rs := conn.Execute(CommandText, cmdText, []); conn.Free; //Give the recordset to the UI thread //Don't forget to add a reference before we stuff it into a 32-bit variable rs._AddRef(); PostMessage(hwndUIThreadWindow, WM_HeresTheRecordsetYouAskedFor, WPARAM(rs), 0); end; 

And then the Recordset is passed to my "main" stream:

 procedure ExecuteComplete(var msg: TMessage); message WM_HeresTheRecordsetYouAskedFor; var rs: _Recordset; begin rs := _Recordset(msg.wParam); //don't forget to remove the manually added reference rs._Release(); ShowMessage(rs.Fields['TheTimeIs'].Value); end; 

I could also do:

 var global_Recordset: _Recordset; var conn: TADOConnection; begin conn := CreateDatabaseConnection(); global_Recordset := conn.Execute(CommandText, cmdText, []); conn.Free; end; 

In any case, the thread that did not create , created the COM object, now uses it. From the main stream:

 global_Recordset .Fields['TheTimeIs'].Value; 

COM denies access to COM objects from apartments (in this case: threads) that did not create the object.

What is the correct way to marshal the interfaces of a COM object while working across apartment boundaries?

+3
source share
1 answer

The correct way to transfer a COM object through apartments is to marshal the interface pointer, which can be done in one of two ways:

  • Ask the worker thread to call CoMarshalInterThreadInterfaceInStream() and pass the received IStream pointer to the user interface thread, which then calls the CoGetInterfaceAndReleaseStream() function.

  • Use the IGlobalInterfaceTable interface. Ask the workflow to create an interface and call its RegisterInterfaceInGlobal() method and pass the resulting cookie to the user interface stream, which then creates the interface and calls its GetInterfaceFromGlobal() and RevokeInterfaceFromGlobal() methods.

+4
source

Source: https://habr.com/ru/post/1489303/


All Articles