0

我从文件中读取数据并将它们写入其他文件。我想用标签显示用户读取行数。它工作。用户可以停止阅读。我使用 backgroundworke,但应用程序不响应停止按钮 - 被冻结。我尝试了 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 为 true

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();
}
4

2 回答 2

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();
    }
}

***编辑

private void stop_Click(object sender, EventArgs e)
    {
         backgroundWorker1.CancelAsync();
        //status = false;           
    }
于 2013-04-28T23:40:13.783 回答
0

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

while (((line = sr.ReadLine()) != null) && (!backgroundWorker1.CancellationPending))
于 2013-04-29T00:22:29.523 回答