异常System.Reflection.TargetInvocationException - Backgroundworker

时间:2013-08-27 17:59:43

标签: c#

我正在尝试使用backgroundworker(bgFileOpener)将openFileDialog打开的文件读入richTextBox(名为websiteInput_rtxt)。

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

当bgWorker仍在运行时关闭表单时会抛出一个似乎没有被捕获的异常, 有人可以告诉我什么是遗失或什么可能导致例外?

异常消息称为“System.Reflection.TargetInvocationException”,而innerException则表示有关RichTextBox的内容。

1 个答案:

答案 0 :(得分:5)

关闭表单不会立即停止后台工作程序,这意味着在表单关闭后仍然可以在表单上引发ProgressChanged事件。

您可以通过以下方式解决此问题:

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