Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on
i usually get this error,,i want to display the thread result to a textbox but i just can't..please help me,,thanks a lot
here's my code:
i usually get this error,,i want to display the thread result to a textbox but i just can't..please help me,,thanks a lot
here's my code:
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace MultiThread
{
public partial class Form1 : Form
{
Thread thread;
public Form1()
{
InitializeComponent();
}
// delegate is used to communicate with UI Thread from a non-UI thread
//public delegate void UpdateTextCallback(string message);
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
// Creates a new thread
thread = new Thread(new ThreadStart(TestThread));
thread.IsBackground = true;
thread.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
thread.Abort();
}
private void TestThread()
{
for (int i = 0; i <= 1000; i++)
{
//Thread.Sleep(1000);
textBox1.Text = textBox1.Text + "Thread";
//textBox1.BeginInvoke(new UpdateTextCallback(UpdateText), new object[] { i.ToString() });
Thread.Sleep(100);
}
}
private void UpdateText(string message)
{
textBox1.Text = message;
}
}
}
Comment