0

I have read this article and I want to ask... How to make this using timer? I dont want to use new thread, but I want use timer.

I do not know how to write code...

Can you help me?

    // 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.";
    }
  • This will likely end up being a duplicate of: http://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c – Special Sauce May 28 '15 at 22:53
  • Marc Gravell's answer on the SO post just linked is probably the simplest way to invoke an action on the UI thread. – Special Sauce May 28 '15 at 22:54

1 Answers1

0

You can use the built in Windows Forms Timer class to handle this.

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

That will update the textbox every 1 second.

Johnathon Sullinger
  • 7,097
  • 5
  • 37
  • 102