4

重複の可能性
: 「クロススレッド操作が無効です: 作成されたスレッド以外のスレッドからアクセスされた lbFolders を制御します。」というエラーが表示されるのはなぜですか?

私はwinformsの初心者です。私のコードでは、進行状況バーをforループで更新していますが、以下に示すように、ループカウントの形式でラベルを更新する必要があります-

パブリック部分クラス Form1 : Form { 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);
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    void Form1_Shown(object sender, EventArgs e)
    {
        // Start the background worker
        backgroundWorker1.RunWorkerAsync();
    }


    // On worker thread so do our thing!
    void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        // Your background task goes here
        for (int i = 0; i <= 100; i++)
        {
            label1.Text = "Trade" + i;
            // Report progress to 'UI' thread
            backgroundWorker1.ReportProgress(i);
            // Simulate long task
            System.Threading.Thread.Sleep(100);
        }
    }
    // Back on the 'UI' thread so we can update the progress bar
    void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // The progress percentage is a property of e
        progressBar1.Value = e.ProgressPercentage;
    }

}

しかし、label1にアクセスしている間、エラーがスローされます-

クロススレッド操作が無効です: コントロール 'label1' は、それが作成されたスレッド以外のスレッドからアクセスされました。

label1 のテキストを更新するにはどうすればよいですか

4

3 に答える 3

7

ワーカー スレッド内ではなく、進行状況ハンドラーでラベルを更新します。

// On worker thread so do our thing! 
 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); 
     } 
 } 
 // Back on the 'UI' thread so we can update the progress bar - and our label :)
 void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) 
 { 
     // The progress percentage is a property of e 
     progressBar1.Value = e.ProgressPercentage; 
     label1.Text = String.Format("Trade{0}",e.ProgressPercentage);
 } 
于 2012-09-27T09:54:34.353 に答える