简体   繁体   English

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

[英]The application is frozen after using BackgroundWorker C#

I read data from file and write them in other file. 我从文件中读取数据,然后将其写入其他文件中。 I want show user number of read lines with label. 我想用标签显示用户读取行数。 It working. 工作正常。 And user can stop reading. 用户可以停止阅读。 I use backgroundworke, but the application does not respond to the Stop button-is frozen. 我使用backgroundworke,但是应用程序不响应“停止”按钮-被冻结。 I tried Aplication.DoEvents(), But I must just need to button 2x to respond. 我尝试了Aplication.DoEvents(),但我只需要按2x即可响应。

start reading 开始阅读

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

reading and writing 读写

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

stop reading set status to false..berofe is true 停止读取设置状态为false..berofe为true

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

BW use 带宽使用

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

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

First of all, are you setting your BackgroundWorker to allow cancellation? 首先,您是否将BackgroundWorker设置为允许取消?

backgroundWorker1.WorkerSupportsCancellation = true;

Then your Do_Work event should look something like this: 然后,您的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;           
    }

In addition to the changes proposed by SOfanatic, and as suggested by mike z, you should be checking for the pending cancellation in readDataArffBig(). 除了SOfanatic提出的更改(如Mike Z所建议的那样),您还应该在readDataArffBig()中检查挂起的取消。 A good place would be right in the while statement: 在while语句中,一个好地方将是正确的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM