简体   繁体   中英

although I am using a background worker GUI still hanging…

I have a GUI Where i have to import some document , but when i do using background worker, the GUI is hanging , which must not happen since I am using a background worker, why this happens? kindly find code below..

void ImportNotes_ContextMenuStripItem_Click(object sender, EventArgs e)
{
    if (!backgroundWorker_notesImport.IsBusy)
    {
        mainFrm.ProgressBar.Visible = true;
        backgroundWorker_notesImport.RunWorkerAsync();
    }
}

private void backgroundWorker_notesImport_DoWork(object sender, DoWorkEventArgs e)
{
    ImportNotes();
}

private void backgroundWorker_notesImport_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    mainFrm.ProgressBar.Value = e.ProgressPercentage;
}

void ImportNotes() { }

Does the ImportNotes() method just do the whole import in one big step?

If so then you still aren't giving the UI chance to do anything. The example from the MSDN shows how it should be used:

    // This event handler is where the time-consuming work is done.
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;

        for (int i = 1; i <= 10; i++)
        {
            if (worker.CancellationPending == true)
            {
                e.Cancel = true;
                break;
            }
            else
            {
                // Perform a time consuming operation and report progress.
                System.Threading.Thread.Sleep(500);
                worker.ReportProgress(i * 10);
            }
        }
    }

You need to have a loop that allows some processing (the Sleep in this case) and a call to ReportProgress .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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