2014-09-23 42 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() })); 
    } 
相關問題