Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using EnterCriticalSection in Thread to update VCL label

I'm new to threads. I'm using a 3rd party library that uses threads which at times call a procedure I've provided.

How do I update update a TLabel.Caption from my procedure when its called by the thread?

If I've called InitializeCriticalSection elsewhere, is it as simple as

  EnterCriticalSection(CritSect);
  GlobalVariable := 'New TLabel.Caption';
  LeaveCriticalSection(CritSect);

And then in my main thread:

  EnterCriticalSection(CritSect);
    Label1.Caption:= GlobalVariable;
  LeaveCriticalSection(CritSect);

But, how do I get the main thread code to be called? The thread can use SendMessage? Or is there some better/easier way (.OnIdle could check a flag set by the thread?)

Thanks.

like image 202
RobertFrank Avatar asked Dec 07 '22 04:12

RobertFrank


1 Answers

Critical Sections are used to serialize accessing to a piece of code. For updating graphical user interface, you should take note that only the main thread should update GUI elements.

So if your thread needs to update a GUI element, it should delegate this to the main thread. To do so, you can use different techniques:

The simplest one is using Synchronize method in your thread code. When Synchronize is called, your thread is paused, the code you provided to Synchronize will be executed in the context of the main thread, and then your thread resumes.

If you don't like your thread get stopped every time that piece of code is called, then you can use Queue method. Queue sends your request to the message queue of the destination thread (here main thread), so your thread will not stop, but the UI might not get updated immediately, depending on how crowded main thread's message queue is.

Another way to achieve this is to send custom Windows messages to the main thread using SendMessage or PostMessage API functions. In that case, you have to define a custom message, and send it to the main thread whenever you need to change a UI element. Your main thread should provide a message handler for that type of message, and handle the received messages. The consequence is something similar to using Queue method.

like image 90
vcldeveloper Avatar answered Dec 15 '22 00:12

vcldeveloper