Reputation: 13
I'm trying to make it so that my form refreshes when I click a button. However I keep getting an error
'Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.'
private void button1_Click(object sender, EventArgs e)
{
worker.DoWork += formReload;
worker.RunWorkerAsync();
}
static BackgroundWorker worker = new BackgroundWorker();
private void formReload(object sender, DoWorkEventArgs ev)
{
this.Refresh();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
}
I've tried to research it, and I get that I have to use the Invoke method, however I don't understand where to put it, and why to use it? Any help would be much appreciated!
Thanks, Jarrod
Upvotes: 0
Views: 1947
Reputation: 7629
Actually your code does nothing, the DoWork
is unnecessary. You can rewrite your code as:
private void button1_Click(object sender, EventArgs e)
{
worker.RunWorkerAsync();
}
static BackgroundWorker worker = new BackgroundWorker();
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (this.InvokeRequired)
this.Invoke(new Action(()=>Refresh()));
}
Assuming that you subscribed the DoWork
method in the contructor using
worker.DoWork += backgroundWorker1_DoWork;
Take note that a Refresh
doesn't change anything. What do you have to refresh?
Upvotes: 4