使用timer,C#对Windows窗体控件进行线程安全调用

时间:2015-05-28 22:42:51

标签: c# multithreading winforms timer

我已阅读this article,我想问......如何使用timer? 我不想使用新线程,但我想使用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.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.";
    }

1 个答案:

答案 0 :(得分:0)

您可以使用内置的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秒更新一次文本框。