In a backgroundworker dowork event i'm starting a timer:
private bool cancelop = false;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bgw = (BackgroundWorker)sender;
int Counter = 0;
int percentage = 0;
int total = allfiles.Count;
for (int i = 0; i < allfiles.Count; i++)
{
if (bgw.CancellationPending == true)
{
pictureBox1.Image.Dispose();
pictureBox1.Image = Properties.Resources.Weather_Michmoret;
e.Cancel = true;
makeGif = false;
cancelop = true;
timer1.Stop();
break;
}
else
{
timer1.Start();
Counter += 1;
percentage = Counter * 100 / total;
bgw.ReportProgress(percentage);
}
}
if (makeGif == true)
{
unfreez.MakeGIF(allfiles, outputfile + DateTime.Now, 8, true);
}
bgw.ReportProgress(100);
e.Result = allfiles;
}
Then in the timer tick event:
private void timer1_Tick(object sender, EventArgs e)
{
try
{
if (cancelop == true)
{
// Cancel the asynchronous operation.
progressBar1.EndColor = Color.FromArgb(210, 0, 0);
label7.ForeColor = Color.Red;
label7.Text = "Operation Has Been Cancelled";
timer1.Stop();
backgroundWorker1.CancelAsync();
}
else
{
this.label7.Visible = !this.label7.Visible;
}
}
catch(Exception errrr)
{
string myer = errrr.ToString();
}
}
The exception message:
[System.InvalidOperationException] = {"Cross-thread operation not valid: Control 'label7' accessed from a thread other than the thread it was created on."}
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.get_ContainsFocus()
at System.Windows.Forms.Control.SelectNextIfFocused()
at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
at System.Windows.Forms.Control.set_Visible(Boolean value)
at Animated_Gifs.Form1.timer1_Tick(Object sender, EventArgs e) in d:\C-Sharp\Animated_Gifs\Animated_Gifs\Animated_Gifs\Form1.cs:line 179
Line 179 is in the timer tick event:
this.label7.Visible = !this.label7.Visible;