本文介绍了我的Timer事件崩溃,因为这些事件是在其他线程上调用的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到错误跨线程操作无效:从创建该线程的线程之外的其他线程访问控件'label1'."当我运行此代码时:

I get the error "Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on." when I run this code:

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";
        }
    }
}

我认为事件与触发事件的线程相同.

I thought events ran in the same thread as they were triggered in.

推荐答案

您可能使用了错误的计时器.尝试使用WinForms计时器,该计时器在GUI线程上运行,因此您不必进行调用

You might be using the wrong kind of timer. Try the WinForms timer, its runs on the GUI thread so you don't have to do Invoke

这篇关于我的Timer事件崩溃,因为这些事件是在其他线程上调用的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 17:58