2014-09-23 30 views
0

我有2个窗体,在Form1中,有很多事务要完成,所以我使用了BackgroundWorker 。所以在行动中采取我想要的窗口2被打开并显示进度条(行动的进展情况),所以我做了这样的:跨线程操作无效:从其创建的线程以外的线程访问控制'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中。问题是,当行动将accompilshed的窗口2(其中contans进度条)应该是封闭的,所以我用

form2.Close(); 

,但我得到这个错误讯息

Cross-thread operation not valid: Control 'Form2' accessed from a thread other than the thread it was created on 

我该如何解决这个问题?

+0

你需要把'form2.Close ()'到'backgroundWorker1.RunWorkerCompleted'事件处理程序中。 – 2014-09-23 05:27:43

+0

这个问题在StackOverflow上每天至少回答几次。我已经将其标记为单一副本 - 但是,请随时点击所有相关问题。 – 2014-09-23 05:32:06

回答

1

使用委托,使其线程安全

if(form2.InvokeRequired) 
    { 
     form2.Invoke(new MethodInvoker(delegate { form2.Close() })); 
    } 
相关问题