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

*爱你&永不变心* 提交于 2019-12-18 09:27:25

问题


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?


回答1:


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.




回答2:


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 
        }
    }



回答3:


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.



来源:https://stackoverflow.com/questions/1809864/how-to-access-a-form-control-from-system-timers-timer-cross-thread-problem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!