简体   繁体   中英

Exception System.Reflection.TargetInvocationException - Backgroundworker

I'm trying to read files which were opened by the openFileDialog into a richTextBox (called websiteInput_rtxt) using a backgroundworker(bgFileOpener).

   private void bgFileOpener_DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {
            foreach (var file in openFileDialog1.FileNames)
            {
                using (StreamReader sreader = new StreamReader(file))
                {

                    // while the stream reader didn't reach the end of the file - read the next line and report it
                    while (!sreader.EndOfStream)
                    {
                        if (bgFileOpener.CancellationPending)
                        {
                            e.Cancel = true;
                            return;
                        }

                        bgFileOpener.ReportProgress(0, sreader.ReadLine() + "\n");
                        Thread.Sleep(15);
                    }
                }
            }
        }
        catch (Exception) { }

    }

    private void bgFileOpener_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
            websiteInput_rtxt.AppendText(e.UserState.ToString());
    }

When the form is closed while the bgWorker is still running an exception is thrown which doesn't seem to be caught , can someone tell me what is missing or what could cause the exception?

Exception message is called "System.Reflection.TargetInvocationException" and the innerException says something about the RichTextBox.

Closing the form doesn't immediately stop the background worker, which means your ProgressChanged event can still be raised on the form after it's been closed.

You can work around this via:

private void bgFileOpener_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    if (this.IsDisposed) // Don't do this if we've been closed already
    {
        // Kill the bg work:
        bgFileOpener.CancelAsync();
    }
    else
        websiteInput_rtxt.AppendText(e.UserState.ToString());
}

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