如何修复 C# 中的跨线程异常? [英] How to fix a cross-thread exception in C#?

查看:34
本文介绍了如何修复 C# 中的跨线程异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 UI 控件上使用 System.Timers.Timer.

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

错误:System.Timers.Timer跨线程操作无效:控制 'txtOutput' 从创建它的线程以外的线程访问."

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

我的代码如下:

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?

推荐答案

您需要设置SynchronizingObject 将计时器的属性设置为表单对象.

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

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

官方文档的相关摘录:

当 Elapsed 事件由可视化 Windows 窗体组件处理时,比如按钮,通过系统线程访问组件pool 可能会导致异常或可能无法正常工作.避免这种情况通过将 SynchronizingObject 设置为 Windows 窗体组件来实现,这会导致处理 Elapsed 事件的方法被调用创建组件的同一个线程.

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.

这篇关于如何修复 C# 中的跨线程异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆