问题
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