Writing To Textbox On Different Thread

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace ThreadingUIUpdate
{
public partial class frmMain : Form
{
Thread thread;
TextBox textBox1;
Button btnStart;

// delegate is used to communicate with UI Thread from a non-UI thread
public delegate void UpdateTextCallback(string message);

public frmMain()
{
InitializeComponent();

AddControlsToForm();
}

private void btnStart_Click(object sender, EventArgs e)
{
if (btnStart.Text == “Start”)
{
// Creates a new thread
thread = new Thread(new ThreadStart(TestThread));
thread.IsBackground = true;
thread.Start();

btnStart.Text = “Stop”;
}
else
{
thread.Abort();

btnStart.Text = “Start”;
}

}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Aborts the thread if the form is closed while the thread is running
thread.Abort();
}

private void TestThread()
{
for (int i = 0; i <= 1000; i++)
{
Thread.Sleep(1000);
textBox1.BeginInvoke(new UpdateTextCallback(UpdateText), new object[] { i.ToString() });
}
}

private void UpdateText(string message)
{
textBox1.Text = message;
}

private void AddControlsToForm()
{
textBox1 = new TextBox();
textBox1.Name = “textBox1”;
textBox1.Text = “Click Start”;
textBox1.Location = new Point(91, 78);
textBox1.Size = new Size(100, 20);

btnStart = new Button();
btnStart.Text = “Start”;
btnStart.Name = “btnStart”;
btnStart.Location = new Point(101, 129);
btnStart.Size = new Size(75, 23);
btnStart.Click += new EventHandler(btnStart_Click);

this.Controls.Add(textBox1);
this.Controls.Add(btnStart);

this.ActiveControl = btnStart;
}
}
}

Advertisements

%d bloggers like this: