How to access a form control from System.Timers.Timer (cross-flow issue)

I am using system.timers.timer for my service.

Now I am creating a test form in which I use it too. In the timer_Elapsed event, I do some work and want to stop the required timer (xxx ms) and write it to the form control to show.

But when I access the list, I get a cross-flow error.

Any ideas?

+1
source share
3 answers

If you want to access the control from a stream other than the main user interface stream, you need to use the Invoke method on the control you want to access.

+1
source

Your method should look like this:

public void foo(int value, string message) { if (InvokeRequired) { BeginInvoke(new Action<int, string>(foo), value, message); } else { // Stop the timer } } 
+1
source

When using System.Timers.Timer, use the SynchronizingObject Timer Property. Apparently, this calls a method that processes the Elapsed event to be called in the same thread in which the assigned component (SynchronizingObject) was created. eg. if myButton is a control of your form (regardless of the main GUI thread),

  System.Timers.Timer myTimer = new System.Timers.Timer(); myTimer.SynchronizingObject = this.myButton; 

this leads to the fact that the Elapsed handler runs in the same thread, removes errors "cross-thread operation".

Pls note: I have very little information about whether this is thread safe, but works fine for me in a specific use case. Hope it helps anyway.

+1
source

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


All Articles