1

I am running a while loop which keeps track of some events forever, In case if i get any exception i am changing its reference to null hoping that the current thread will be aborted and the new reference of that thread will be created. Is it correct or any better way to abort the current thread and start a newer one.

I am trying to do this:

Thread th;

Main()
{
    th = new thread(myfunction);
    th.Start();
}

void myfunction()
{
    while(true)
    {
        try
        {
            // something interesting here.
        }
        catch(exception)
        {
            th = null;
        }
    }
}
1
  • Why do you want to create a new thread? May 11, 2012 at 12:29

4 Answers 4

1

Only thing that will happen is that Thread will remain inaccessible from the Enclosing class.

If there are no further processing, doing so will make the thread out of reach from GC appllication roots. This makes object available for garbage collection in next GC trigger.

1
  • This might indeed be more accurate than my answer. The thread object might be collected, while the actual code (the real windows thread) keeps running.
    – Steven
    May 11, 2012 at 5:16
1

You need to do:

return;

instead of:

th = null;

Because the thread will keep on running. The thread object will not get collected, since it will stay referenced as long as the code is running.

1

Clean up anything you need to for that thread, then break out of the while loop like this:

void runningOnThread()
{
    while (true)
    {
        try
        {
            //...
        }
        catch (Exception e)
        {
            break;
        }
    }

    //thread cleanup code goes here, if you have any.
}

It would be a good idea to log the exception when you catch it. That way you know when you've hit an exception.

3
  • 2
    Not catching all exceptions can result in an rude app domain shutdown, because that is the default behavior of the CLR 2. It migh be better to log that exception (and depending on the type of application either.continue or let the app domain die).
    – Steven
    May 11, 2012 at 5:13
  • @Steven interesting, when I mentioned that I wasn't thinking about it specifically with threading... generally good practice is to catch the exceptions you can handle and throw the rest, but it makes sense that this would be opposite inside a separate thread. Updating my answer... May 11, 2012 at 5:37
  • Absolutely. The general rule is to only catch exceptions you can handle, but handling exceptions around thread boundries needs a little bit more care.
    – Steven
    May 11, 2012 at 7:05
1

First, if you run into an exception, before worrying about starting a new thread, be sure that you actually handle the exception and ensure that the restarted thread will be able to run successfully. Otherwise, you're just going to get a constant stream of crashing threads, and a choppy program while it handles the exception parade. Just some food for thought.

Now, answering the question, best case nulling the reference to the thread will just leave you in an infinite loop, worst case you try to use 'th' later and you get an exception because it's null. Nulling the reference to the thread won't somehow make it aware that it needs to restart itself any more than nulling a reference to parameter you gave it as a function argument will. If you absolutely need some kind of ability to abort/restart the thread, look into doing one of:

  1. raising an event when the thread crashes and break out of the while loop, or
  2. setting a boolean/enum flag saying what the thread is doing, and have the main thread check on it every so often to make sure it hasn't been set to the error state.

This is code is completely off the top of my head, isn't that good, but will give you the general idea:

delegate void ThreadCrashedEvent();
Event ThreadCrashedEvent threadCrashed;

Thread th;

Main()
{
    threadCrashed += OnThreadCrashed();
    th = new thread(myfunction);
    th.Start();
}

void OnThreadCrashed()
{
    th = new thread(myfunction);
    th.Start();
}

void myfunction()
{
    while(true)
    {
      try
      {
          LetsGetDangerous();
      }
      catch(exception)
      {
          if(threadCrashed != null)
          {
              threadCrashed();
              return;
          }
      }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.