我有2个表单,在Form1中,有很多事务需要完成,所以我使用了BackgroundWorker。所以在采取行动期间,我希望打开form2并显示进度条(动作的进度),所以我这样做了:
这是Form1
public partial class Form1 : Form
{
Form2 form2 = new Form2();
public Form1()
{
InitializeComponent();
Shown += new EventHandler(Form1_Shown);
// To report progress from the background worker we need to set this property
backgroundWorker1.WorkerReportsProgress = true;
// This event will be raised on the worker thread when the worker starts
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
// This event will be raised when we call ReportProgress
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
void Form1_Shown(object sender, EventArgs e)
{
form2.Show();
// Start the background worker
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Your background task goes here
for (int i = 0; i <= 100; i++)
{
// Report progress to 'UI' thread
backgroundWorker1.ReportProgress(i);
// Simulate long task
System.Threading.Thread.Sleep(100);
}
form2.Close();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// The progress percentage is a property of e
form2.progressBar1.Value = e.ProgressPercentage;
}
}
我在form2中有一个Progressbar,它的修饰符是公共的。问题是,当动作被合并时,form2(其中包含进度条)应该被关闭,所以我用了
form2.Close();
但我收到此错误消息
Cross-thread operation not valid: Control 'Form2' accessed from a thread other than the thread it was created on
我该如何解决这个问题?
答案 0 :(得分:1)
使用委托使其线程安全
if(form2.InvokeRequired)
{
form2.Invoke(new MethodInvoker(delegate { form2.Close() }));
}
答案 1 :(得分:0)