How to access a form-control from System.Timers.Timer (cross thread problem)

StackOverflow https://stackoverflow.com/questions/1809864

  •  05-07-2019
  •  | 
  •  

Question

I use the system.timers.timer for my service.

Now I build a test-form in which I use it too. In the timer_Elapsed Event I do some work and want to stop the timer it need (xxx ms) and write it on the form control to show.

But when I access the listview, I get an cross thread error.

Any ideas?

Was it helpful?

Solution

If you want to acces a control from a thread other than the main UI thread, you need to use the Invoke method on the control you want to access.

OTHER TIPS

Your method should look like:

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

When using System.Timers.Timer, Use the SynchronizingObject Property of the timer. Apparently this causes the method that handles the Elapsed event to be called on the same thread that the assigned component (SynchronizingObject) was created on. eg. if myButton is a control on your form (whatever main GUI thread),

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

this causes the Elapsed handler to run on the same thread , removes some 'cross thread operation' errors.

Pls Note: I have very little knowledge on whether this is thread safe, but worked fine for me in a Specific use case. Hope it helps anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top