timer and criticalsection

Hi,
my software runs 2 threads and I use a global criticalsection object to share the common variables but when I use a timer to write the common variables to the UI
become that error:

The thread which Entered the CriticalSection must be the thread to Leave the CriticalSection

Timer control code:

Sub Action()
Critical.Enter 'Critical is the Criticalsection object
TextArea3.text = testo
critical.Leave
End Sub

Usually, if a thread enters in the criticalsection, the other threads are waiting until the criticalsection is leaved.

Why this doesn’t work with timer ?

Thanks

The timer’s Action event is always running in the main thread. CriticalSection is used within subclasses of threads where you create more than one instance of it. So this will do:

Sub Action() TextArea3.text = testo End Sub

The variable named “testo” is shared between 2 threads and the main thread.

I have to use Criticalsection !!!

I would say no, because you are only reading “testo”.

And before entering a CriticalSection you should use TryEnter.

In general I would say that you only need a CriticalSection when you write to more than one variable and these variables need to stay in a consistent state. If you just update one variable in Action events of Timers in different threads, there is no need for CriticalSection (because Action events of Timers run on the main thread).

Hi Sacha,
just for curiosity the same happens also when using a Semaphore instead of a CriticalSection?

I have tryed with TryEnter and now it works (I have tested that only 5 time)

Why the timer’s behavior is not the same like another thread?

The timer runs in a separate thread? (not in the main threa ?)

Must I declare the criticalsection object in the app property? (not in a window property?)