使用BackgroundWorker C#后应用程序被冻结

时间:2013-04-28 23:11:15

标签: c# multithreading

我从文件中读取数据并将其写入其他文件中。我想用标签显示读取行的用户数。它工作。用户可以停止阅读。我使用backgroundworke,但应用程序没有响应Stop按钮 - 被冻结。我尝试过Aplication.DoEvents(),但我必须按2x才能响应。

开始阅读

private void button1_Click(object sender, EventArgs e)
{
    string ext = Path.GetExtension(openFileDialog1.FileName);
    if (ext == ".arff")
    {
        getColumn();
        backgroundWorker1.RunWorkerAsync();
    }
}

阅读和写作

private void readDataArffBig()
{            
    int lines = 0;
    StreamWriter sw = new StreamWriter(tempFile, true);
    using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
    {
        while ((line = sr.ReadLine()) != null)
        {
            lines++;
            backgroundWorker1.ReportProgress(lines);
            if (status == false)
                break;
            sw.WriteLine(line)}
        }
}

停止将设置状态读取为false..berofe为真

private void stop_Click(object sender, EventArgs e)
{
    status = false;           
}

BW使用

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    readDataArffBig();
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    label8.Text = e.ProgressPercentage.ToString();
    label8.Refresh();
}

2 个答案:

答案 0 :(得分:0)

首先,您是否将BackgroundWorker设置为允许取消?

backgroundWorker1.WorkerSupportsCancellation = true;

然后你的Do_Work事件应该是这样的:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
     BackgroundWoker bgw = sender as BackgroundWorker;
    if(bgw.CancellationPending)
    {
       e.Cancel = true;
       return;
    }
    else
    {
      readDataArffBig();
    }
}

*** EDIT

private void stop_Click(object sender, EventArgs e)
    {
         backgroundWorker1.CancelAsync();
        //status = false;           
    }

答案 1 :(得分:0)

除了SOfanatic提出的更改以及mike z建议的更改之外,您应该检查readDataArffBig()中的挂起取消。在while语句中,一个好地方就是正确的:

while (((line = sr.ReadLine()) != null) && (!backgroundWorker1.CancellationPending))