1

I am unable to get the reason for this Exception:

private void bwWorker_DoWork(object sender, DoWorkEventArgs e)
{
   if (Main.bolDebugMode)
      MessageBox.Show("Function DoWork is called");
   if (Main.ftpsync(Main.strUsername407, Main.strPassword407, sender as BackgroundWorker) == 0)
      e.Result = e.Result + "No error in " + Main.strUsername407;
   else
   {
      if (Main.bolDebugMode)
         MessageBox.Show("Errors in " + Main.strUsername407);
      e.Cancel = true;
      e.Result = e.Result + "Errors in " + Main.strUsername407;
      if (Main.bolDebugMode)
         MessageBox.Show("Errors marked");
      try
      {
         MessageBox.Show("Next step throws exception");
         return;
      }
      catch (Exception error)
      {
          if (error.ToString() != null)
             MessageBox.Show(error.InnerException.Message);
      }
   }
}

It throws this exception:

An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll

Additional information: Exception has been thrown by the target of an invocation.

The target (to my limited understanding) is the backgroundworker's RunWorkerCompleted function:

 private void bwWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (Main.bolDebugMode)
                MessageBox.Show("DoWork Completed. Break: " + e.Cancelled + " Error: " + e.Error + " Result: " + e.Result);

            // First, handle the case where an exception was thrown.
            if (e.Error != null)
            {
                lStatus.Text = e.Error.Message;
            }
            else if (e.Cancelled)
                lStatus.Text = "Cancelled: " + e.Result.ToString();
            }
            else
            {
                lStatus.Text = "Done! " + e.Result;
                Thread.Sleep(Convert.ToInt16(Main.strGlobalWaitTime));
                pbProgress.Value = 0;
                lStatus.Text = "";
            }

            if (Main.bolDebugMode)
                MessageBox.Show("Analysis completed");

            // Enable the Start button.
            btnStart.Enabled = true;

            // Disable the Cancel button.
            btnCancel.Enabled = false;
        }
public class Main
{
    #region Variables
    // Variables - FTP Settings
    // Reading tons of variables from a appconfig file like so:
    private static string StrGlobalWaitTime = ConfigurationManager.AppSettings["program_globalWaitTime"]; 
    private static bool BolDeleteRemoteFiles = Convert.ToBoolean(ConfigurationManager.AppSettings["program_deleteremotefiles"]);

    // Configuring the variables to receive and write
    public static string strGlobalWaitTime
    {
        get { return StrGlobalWaitTime; }
        set { StrGlobalWaitTime = value; }
    }
    #endregion

    #region Main function
    public static int ftpsync(string strUsername, string strPassword, BackgroundWorker bwWorker)
    {
        if (Directory.EnumerateFiles(strWorkDirectory, "*.pdf").Any())
        {
            bwWorker.ReportProgress(0, "Files left! Upload not complete");
            Thread.Sleep(Convert.ToInt16(Main.strGlobalWaitTime));
            return 1;
        }

However, it doesn't even reach the first debugging message box. Thus it must be happening between the return and the beginning of the function. Is he background worker not handing over directly to the RunWorkerCompleted function? Can anyone tell me what I am missing or doing wrong?

This is my first question. I will try to provide as much information as possible. Google searches for the most obvious queries have been done.
RobSteward
  • 305
  • 3
  • 11
  • You can't be accessing GUI controls in the DoWork method since that is on a different thread. Pass all of the information you need as a parameter when you call your [RunWorkerAsync](https://msdn.microsoft.com/en-us/library/f00zz5b2(v=vs.110).aspx). – LarsTech Dec 15 '16 at 19:27
  • As far as I know I am not accessing any GUI controls in my DoWork. The "Main."xx are all parts of a separate class. – RobSteward Dec 15 '16 at 20:00
  • Calling `MessageBox.Show` *is* accessing GUI thread. – Crono Dec 15 '16 at 20:03
  • We don't know much about that Main class of yours. – LarsTech Dec 15 '16 at 20:07
  • You will want to learn how to use `Enum` types next. :) – Crono Dec 15 '16 at 22:02
  • I added the Main.cs class. The return is acutally in the first lines of the main class function called "ftpsync". There I check a folder for pdf content and if found return with a "1" for "not without errors". As for the message box: I do get the "Next step throws exception" message box. I do not get the one in RunWorkerCompleted. The content of this basically copied from msdn: [link]https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.runworkercompleted(v=vs.110).aspx[/link] – RobSteward Dec 15 '16 at 22:04
  • Also Crono, your very cryptic comment meeeeans? I will, since I am guessing there is something to take away, but looking at it first glance I am unable to see the connection to this case. – RobSteward Dec 15 '16 at 22:16
  • @Crono - MessageBox.Show is a static method and explicitly specified to be thread-safe. – H H Dec 15 '16 at 22:19

1 Answers1

3

The thing to look for whenever you encounter a TargetInvocationException is the InnerException property, which will have the "real" exception.

From the look of it, it will most likely have something to do with trying to access the GUI from inside the worker's thread. Remember that when using the DoWork handler, the code executes in a different thread from the main UI's. Therefore, calls to GUI components must be either done via Invoke calls or avoided all together.

Crono
  • 10,211
  • 6
  • 43
  • 75
  • I tried getting to the InnerException - but not success since I do not get the error msg at all. – RobSteward Dec 15 '16 at 20:00
  • 1
    Is the debugger set for breaking on exceptions as they occur? If so you should have access to the full exception instance through watch tool window. – Crono Dec 15 '16 at 20:03
  • How do you know you have a `TargetInvocationException` in the first place? – Crono Dec 15 '16 at 20:05
  • http://imgur.com/a/4boJq and for explanation: frmMain is my the only form I have. It contains the backgroundworker bwWorker and all the according functions like DoWork, RunWorkerCompleted, ProgressChanged, etc. – RobSteward Dec 15 '16 at 22:23