System.Reflection.TargetInvocationException - Backgroundworker exception

I am trying to read files opened by openFileDialog in a richTextBox (called websiteInput_rtxt) using 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 bgWorker is still running, an exception is thrown that doesn't seem to be caught , can someone tell me what is missing or what might throw an exception?

The exception message is called "System.Reflection.TargetInvocationException", and innerException says something about the RichTextBox.

+4
source share
1 answer

Closing the form does not immediately stop the background worker, which means that your ProgressChanged event can still be raised in the form after closing it.

You can get around this by:

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

Source: https://habr.com/ru/post/1499206/


All Articles