Exception System.Reflection.TargetInvocationException - Back

本文关键字:Back TargetInvocationException Reflection System Exception | 更新日期: 2023-09-27 18:29:24

我正在尝试使用后台工作者(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的一些内容。

Exception System.Reflection.TargetInvocationException - Back

关闭窗体不会立即停止后台工作程序,这意味着在窗体关闭后,仍然可以在窗体上引发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());
}