作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我收到错误消息“跨线程操作无效:从创建它的线程以外的线程访问控件‘label1’。”当我运行这段代码时:
using System;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Timers;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
System.Timers.Timer T = new System.Timers.Timer();
public Form1()
{
InitializeComponent();
T.Elapsed += new ElapsedEventHandler(T_Elapsed);
T.Start();
}
void T_Elapsed(object sender, ElapsedEventArgs e)
{
label1.Text = "This will not work";
}
}
}
我认为事件在触发时在同一个线程中运行。
最佳答案
我们在 NET 中有 3 个定时器类(Timers.Timer、Threading.Timer 和 Windows.Forms.Timer),但只有 Windows.Forms 类有 Tick 事件。
正常使用时(即在设计时拖动到表单或在某些表单代码中创建)事件在主线程上运行,您的问题应该不会发生。
因此,您很可能在另一个线程中创建了 Timer 对象,您可能应该编辑您的问题以向我们展示您如何/在何处创建它,并告诉我们它是否是故意在另一个线程中。
关于c# - 我的计时器事件崩溃,因为事件是在不同的线程上调用的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1349305/
我是一名优秀的程序员,十分优秀!