[python-win32] COM server with events and multiple threads

Mark Hammond mhammond at skippinet.com.au
Fri Jun 3 01:30:38 CEST 2005


> I attached a zip file that contains a small python COM server and a
> small VB6 client that reproduces the problem.
>
> The server sends events to the VB6 client, but the problem is
> the events
> are handled in different threads in the VB6 client.
>
> I would appreciate it if someone could tell me what are the minimal
> changes I need to make to this sample so that each event is
> handled in
> the same GUI thread.

The problem is that the connection server is getting an interface object on
one thread (the main thread as part of the Advise call) - but the new
threads you create are using these objects without marshalling the objects.

ie, your new threads are referencing objects "owned" by another thread.
This is why the calls are being delivered to VB on the wrong thread.  If you
marshalled the objects to the new thread, that marshalling would ensure VB
received the call on the correct thread.

You marshall the COM object by using CoMarshalInterThreadInterfaceInStream
and CoGetInterfaceAndReleaseStream.

win32com.server.connect wasn't really designed for this case -
'self.connections' can only be used directly or indirectly by thead the
Advise call was made on.  Each thread must have its own copy of the
interfaces in self.connections, passed to it via
CoMarshalInterThreadInterfaceInStream.  This will be tricky to work with new
connections established after the thread has started.  One option may be a
queue - the "main" thread could queue CoMarshalInterThreadInterfaceInStream
wrapped objects, and the worker thread could dequeue the objects and call
CoGetInterfaceAndReleaseStream before attempting to use the object.

If you could make sensible modifications to win32com.server.connect to
support that scenario, I'd be happy to integrate them.  You may find it
easier to "fork" that class for your own purposes though.

> Also what would be some good COM books to read that are
> relevant to this
> subject?

Not sure about entire books.  I have explained these COM rules before in
this thread ;)  "Python Programming on Win32" also covers this in some
detail.  A google seatch for "COM threading model" returns a number of hits
from good sites that seem fairly useful.  A good starting point at MSDN
might be:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/com/html/7b
d6f62f-8c91-44bd-9a7f-d47988180eed.asp


Mark



More information about the Python-win32 mailing list