开发者

Simple background thread restarting in .NET

I'm working on an WPF application that has a few threads that are processing information in the background. If one of the threads crashes, it brings down the app. I'm going to correct that by wrapping the function passed to threadstart in a try/catch.

However, I was wondering if I could do one better. It should be possible to write a simple function that will restart a thread if it fails. It would be pretty simple to even put some rules in to try a restart immediately, and then delay on subsequent restart attempts. Basically, it would act as a very basic service control manager for a single thread.

Note: by "restart", I mean simply call the method again on开发者_运维知识库 a new thread.

Are there any problems with this approach? Are there any existing solutions out there that I should evaluate before writing this myself?

I only ask because this doesn't seem like a new problem.


I think there is a more fundamental problem here:

If the thread throws when it's run the first time, chances are it'll throw the same exception if you call it the same way with the same data. Rerunning the exact same thing that just failed is usually not a good idea.

If the exception is truly caused by something that will not happen the second time, then there isn't a problem with retrying. However, there is little reason to spawn a new thread - just have your thread (in it's try/catch) retry the operation. You can do this easily in a simple loop - a naive implementation (wouldn't recommend this, as it might never end, but it can give you the right idea) could be:

bool failed = false;
do
{
   try
   {
       failed = false;
       DoDangerousOperation();
   }
   catch(MyException e)
   {
       failed = true;
   }
} while (failed);

If not, there is some other issue you should try to debug, most likely a subtle race condition caused by your multithreading.


You do need to have a try/catch around all thread entry points to prevent crashes. This includes calls to Thread.Start, ThreadPool.QueueUserWorkItem, BeginInvoke, async callbacks, etc. Also don't forget finalizers, an error there will crash the app too.

As far are "restarting" the thread, that can be extremely dangerous. Doing it for all threads means you won't know what has happened already or what state the application is in and you could compound whatever problem caused the exception in the first place. It's also unlikely to succeed unless the exception is temporary, like networking or resource based.

Targeted retries are useful though for specific types of actions that can error out temporarily.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜