-1

ListViewバックグラウンドワーカーを使用して、ボタンがクリックされた後に各アイテムをループし、作業を行います。

private void bParsePosts_Click(object sender, EventArgs e)
{
    parseWorker.RunWorkerAsync(this.lvPostQueue);
}

で、〜がある:

private void parseWorker_DoWork(object sender, DoWorkEventArgs e)
{
    // Loop through each item
    for (int i = 0; i < lvPostQueue.Items.Count; i++)
    {
        string title = lvPostQueue.Items[i].SubItems[0].ToString();
        string category = lvPostQueue.Items[i].SubItems[1].ToString();
        string url = lvPostQueue.Items[i].SubItems[2].ToString();

        lvPostQueue.Items[i].SubItems[3].Text = "Done";
    }
}

ただし、次のエラーが表示されます。

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

lvPostQueueそのバックグラウンド ワーカー内からコントロールを操作するにはどうすればよいでしょうか。

ありがとう。

4

2 に答える 2

0

スレッド セーフな呼び出しを使用するだけです: http://msdn.microsoft.com/en-us/library/ms171728.aspx

例:

// This event handler starts the form's  
        // BackgroundWorker by calling RunWorkerAsync. 
        // 
        // The Text property of the TextBox control is set 
        // when the BackgroundWorker raises the RunWorkerCompleted 
        // event. 
        private void setTextBackgroundWorkerBtn_Click(
            object sender, 
            EventArgs e)
        {
            this.backgroundWorker1.RunWorkerAsync();
        }

        // This event handler sets the Text property of the TextBox 
        // control. It is called on the thread that created the  
        // TextBox control, so the call is thread-safe. 
        // 
        // BackgroundWorker is the preferred way to perform asynchronous 
        // operations. 

        private void backgroundWorker1_RunWorkerCompleted(
            object sender, 
            RunWorkerCompletedEventArgs e)
        {
            this.textBox1.Text = 
                "This text was set safely by BackgroundWorker.";
        }
于 2012-08-26T00:00:29.353 に答える
0

正しい答えは次のとおりです。

private void bParsePosts_Click(object sender, EventArgs e)
{
    parseWorker.WorkerReportsProgress = true;
    parseWorker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
    parseWorker.RunWorkerAsync();
}

private void parseWorker_DoWork(object sender, DoWorkEventArgs e)
{
    // Loop through each item
    for (int i = 0; i < lvPostQueue.Items.Count; i++)
    {
        string title = lvPostQueue.Items[i].SubItems[0].ToString();
        string category = lvPostQueue.Items[i].SubItems[1].ToString();
        string url = lvPostQueue.Items[i].SubItems[2].ToString();

        parseWorker.ReportProgress(i * 100 / lvPostQueue.Items.Count, i);
    }
}

void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    var i = (int)e.UserState;
    lvPostQueue.Items[i].SubItems[3].Text = "Done";
}
于 2012-08-26T06:18:33.270 に答える