AgainMe AgainMe - 3 months ago 14
C# Question

Check if a thread is running recursively?

I've a main thread called t1:

Thread t1 => new Thread(UpdateResults);


that execute a method called
UpdateResult
this method require internet connection. Now sometimes the connection could be broken.

When the connection is down, the method
UpdateResult
return an exception and the thread
t1
terminate the execution.

I need to execute again the thread
t1
so I though to create another thread
t2
that check recursively if the thread
t1
is running or no.

Both thread are started automatically. This is the code of thread
t2
method:

while (true)
{
if (!t1.IsAlive)
{
t1.Start();
}
}


this code unfortuntely slow down the app UI, 'cause is an infinite loop.
What I can do instead for fix this?

Answer

Instead of wasting another thread t2 just to watch t1, you may consider to change the method of thread t1:

Thread t1 = new Thread(o =>
{
    while (true)
    {
        try
        {
            UpdateResult();
        }
        catch (Exception)
        {
            // do some error handling
        }
        Thread.Sleep(100);
    }
});

So you catch the exception (without rethrowing it!) and prevent the crash of the whole thread.

This is of course only a simple example. You should try to catch only the specific exception for a broken connection and add proper error handling (e.g. logging etc.).
And adjust the time the thread should sleep according to your needs.

Comments