Assuming I have a form named Form1:
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void UpdateText(object text)
- {
- button1.Text = text.ToString();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- Thread th = new Thread(new ParameterizedThreadStart(UpdateText));
- th.IsBackground = true;
- th.Start("hello world");
- }
- }
Run the form, i got error "InvalidOperationException was unhandled"
Cross-thread operation not valid: Control 'button1' accessed from a thread other than the thread it was created on.
I fix the above error using the following lines:
- private delegate void UpdateTextDel(object text);
- private void UpdateText(object text)
- {
- if (button1.InvokeRequired)
- button1.Invoke(new UpdateTextDel(UpdateText), text);
- else
- button1.Text = text.ToString();
- }
Comments