Hi,
I have an object class which is designed to be used concurrently by multiple
threads. It owns a critical section which threads can use to acquire
exclusive access to the object before calling one of the object's methods.
The class also exposes an event intended to be used to hold an event handler
that updates the user interface.
The problem is how to dispatch the event handler in a thread-safe way. The
obvious solution is to call the TThread class method Synchronize, but
because my class is not a thread class descendent, it does not have a thread
object that it can pass to the Synchronize method. I need to somehow
retrieve the current thread in which my event handler dispatcher is
running, so that it can be passed to the Synchronize method. I have found
the procedure GetCurrentThreadID, but this returns the ID of the current
thread. Is there a way of converting a thread handle or ID to a thread
object? (I doubt it, but I ask the question anyway). Or is there a
Synchronize method equivalent that can be passed a thread handle or ID in
lieu of a TThread object?
I can see that an alternative approach could be not to attempt to call the
event dispatcher from the thread that it happens to be running in, but to
post a message to the application window to ensure that the event handler is
executed in the main thread.
I note in passing that it would be very nice if a critical section object
were to expose the threads that are waiting on it. An elegant solution could
then have been to retrieve the current thread from the critical section,
assuming that the current thread is the thread which currently has ownership
of the critical section. I would have thought that under the hood a critical
section must contain a queue of waiting threads. But unfortunately the
Delphi TCriticalSection exposes none of this.
Any suggestions about how to dispatch the event handler in a thread-safe
manner?
TIA,
EM