C# 使用计时器C对Windows窗体控件进行线程安全调用#

C# 使用计时器C对Windows窗体控件进行线程安全调用#,c#,multithreading,winforms,timer,C#,Multithreading,Winforms,Timer,我已经读过了,我想问。。。如何使用计时器进行此操作? 我不想使用新线程,但我想使用定时器 我不知道如何写代码 你能帮我吗 // This event handler creates a thread that calls a // Windows Forms control in an unsafe way. private void setTextUnsafeBtn_Click( object sender, EventArgs e)

我已经读过了,我想问。。。如何使用
计时器进行此操作?
我不想使用新线程,但我想使用
定时器

我不知道如何写代码

你能帮我吗

    // This event handler creates a thread that calls a 
    // Windows Forms control in an unsafe way.
    private void setTextUnsafeBtn_Click(
        object sender, 
        EventArgs e)
    {
        this.demoThread = 
            new Thread(new ThreadStart(this.ThreadProcUnsafe));

        this.demoThread.Start();
    }

    // This method is executed on the worker thread and makes
    // an unsafe call on the TextBox control.
    private void ThreadProcUnsafe()
    {
        this.textBox1.Text = "This text was set unsafely.";
    }

您可以使用内置的Windows窗体
Timer
类来处理此问题

public partial class Form1 : Form
{
    private System.Windows.Forms.Timer timer;
    public Form1()
    {
        InitializeComponent();
        this.timer = new System.Windows.Forms.Timer();
        this.timer.Interval = 1000; // 1 second.
        this.timer.Tick += OnTimerFired;
        this.timer.Start();
    }

    private void OnTimerFired(object sender, EventArgs e)
    {
        this.textBox1.Text = "This was set safely.";
    }
}

这将每1秒更新一次文本框。

这很可能会重复:Marc Gravell在刚才链接的帖子上的回答,因此这可能是在UI线程上调用操作的最简单方法。