开发者

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

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

N开发者_Go百科ow 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?


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜