views:

125

answers:

4

Hi

I have the following code:

public Mainform()
{
...
        // scheduler
        scheduler.DoWork += new System.ComponentModel.DoWorkEventHandler(scheduler_DoWork);
        scheduler.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(scheduler_RunWorkerCompleted);
        scheduler.WorkerReportsProgress = false;
        scheduler.WorkerSupportsCancellation = true;
...

...

    scheduler_DoWork(this, null);
    scheduler.RunWorkerAsync(1000);

...
}    

void scheduler_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            scheduler_Enabled = false;
            CustomExceptionHandler eh = new CustomExceptionHandler();
            eh.HandleUnhandledException(e.Error, "scheduler");
        }
        if(scheduler_Enabled)  
        {
            scheduler.RunWorkerAsync(1000);
        }
    }


void scheduler_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{

 try
 {            
    try
    {
      ...do some stuff
    }
    catch(MyException ex)
    {
       ThreadSafeShowError();
    }
    finally
    {}
    ...do more stuff
 }
 finally
 {
   if (e != null && e.Argument != null)
   {
    Thread.Sleep((int)e.Argument);
   }
 }
}

The backgroundworker thread died unexpectedly without any exception being thrown. I did not encounter this problem during development and it seems to be hard to reproduce. I suspected that maybe a cross thread exception was occurring when I am doing work in the scheduler_DoWork. I have tried to explicitly update the UI without checking if InvokeRequired and the thread continues to run without problems in a release build. How can this be? (Cross thread exception should occur) How can I determine what causes the thread to die? Any suggestions on how to figure out what is going wrong or how to debug this issue will be appreciated?

+1  A: 

The RunWorkerCompleted event might not be fired on the UI Thread. If it is not, then the thread will end and your scheduler object will be garbage collected, which will make it seem like it just quit with no error. See this post for more details. Here and here are SO posts about this.

SwDevMan81
A: 

In Mainform, you never call scheduler.RunWorkerAsync, so your BackgroundWorker does not start at all.

luvieere
A: 

Your sample doesn't show enough code to determine what's going on but:

  • Maybe an exception is being thrown from ThreadSafeShowError? Why are you trying to show an error from the worker thread anyway - the conventional thing to do is to show e.Error if not null in the RunWorkerCompleted event handler.

To debug the issue try putting the following around all the code in your DoWork handler:

try
{
   // do work
   // log a trace statement here
}
catch(Exception ex)
{
   // log exception, e.g. with System.Diagnostics.Debug.Write
   throw;
}
finally
{
   // log a trace statement here
}
Joe
A: 
Groo