How to fix a cross-thread exception in C#? [duplicate]

安稳与你 提交于 2019-12-13 22:25:24

问题


I'm trying to use System.Timers.Timer on a UI control.

The error: System.Timers.Timer "Cross-thread operation not valid: Control 'txtOutput' accessed from a thread other than the thread it was created on."

My code is the following:

System.Timers.Timer timeRandomEvent = new System.Timers.Timer(10 * 1000); 

// timer for random events  
timeRandomEvent.Elapsed += new ElapsedEventHandler(timeRandomEvent_Elapsed);
timeRandomEvent.Start();

void timeRandomEvent_Elapsed(object sender, ElapsedEventArgs e) 
{
    wl("Adding some text to a text box.");   // Exception occurs here
}

Is there a way to allow it, or another alternative that's hopefully easy?


回答1:


You need to set the SynchronizingObject property of your timer to your form object.

timer.SynchronizingObject = this; // Synchronize the timer with this form UI

Relevant excerpt from the official documentation:

When the Elapsed event is handled by a visual Windows Forms component, such as a button, accessing the component through the system-thread pool might result in an exception or just might not work. Avoid this effect by setting SynchronizingObject to a Windows Forms component, which causes the method that handles the Elapsed event to be called on the same thread that the component was created on.



来源:https://stackoverflow.com/questions/24085983/how-to-fix-a-cross-thread-exception-in-c

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