A background worker is a different thread than your windows form. Therefor you need to let your background worker somehow return information back to the main thread.
In the example below, I use the reportProgress functionality of the backgroundworker, as the event is triggered on the windows form thread.
public partial class Form1 : Form
{
enum states
{
Message1,
Message2
}
BackgroundWorker worker;
public Form1()
{
InitializeComponent();
worker = new BackgroundWorker();
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
worker.WorkerReportsProgress = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
//Fake some work, report progress
worker.ReportProgress(0, states.Message1);
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
states state = (states)e.UserState;
if (state == states.Message1) MessageBox.Show("This should hold the form");
}
private void button1_Click(object sender, EventArgs e)
{
worker.RunWorkerAsync();
}
}
Note: The background worker will NOT halt at reportProgress. If you want your bgworker to wait until the mbox is pressed, you need to make a halt something manually for it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…