I'm trying to get background worker functioning in the most basic way with a windows form, for instance get a background process to change text in a label.. I got the basic background worker code here.. http://www.albahari.com/threading/part3.aspx Heres the code in my form.. Trying to make it so you press a button and then background worker thread is spawned which changes text in the label
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;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
BackgroundWorker _bw = new BackgroundWorker();
void backgroundio()
{
_bw.DoWork += bw_DoWork;
_bw.RunWorkerAsync("Message to worker");
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
// This is called on the worker thread
label1.Text = (string)(e.Argument); // writes "Message to worker"
// Perform time-consuming task...
}
void button1_Click(object sender, EventArgs e)
{
backgroundio();
}
}
}
For the label1.Text = (string)(e.Argument); I get this error.
Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.
Thank for any help !! :)
Actually while I'm here can somebody explain this line?
_bw.DoWork += bw_DoWork;
I dont get how += makes any sense in this context. how can you add those things?
Answered exact question
. Full BkWorker sample is there - stackoverflow.com/a/11033200/763026. In Do_Work you cannot access UI. See the sample in my SO post. Copy-Past and run it. – Angshuman Agarwal