在backgroundworker dowork事件中,我正在启动计时器:
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;
}
然后在计时器刻度事件中:
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();
}
}
异常消息:
[System.InvalidOperationException] = {“跨线程操作无效:控制'label7'从其创建的线程以外的线程访问。”}
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
第179行在计时器刻度事件中:
this.label7.Visible = !this.label7.Visible;