gpt4 book ai didi

c# - 我的计时器事件崩溃,因为事件是在不同的线程上调用的

转载 作者:行者123 更新时间:2023-11-30 19:22:21 25 4
gpt4 key购买 nike

我收到错误消息“跨线程操作无效:从创建它的线程以外的线程访问控件‘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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com