当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - 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?

网友答案:

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.

网友答案:

One approach to avoid an infinite polling is to Join the thread, and re-spawn it when it stops:

while (true) {
    t1.Join();
    t1 = ... // Make a replacement thread
    t1.Start();
}

It goes without saying that this should not be done from UI thread, because Join() blocks indefinitely.

网友答案:

If you want to stick with your architecture, something as simple as waiting a second in each loop of Thread t2 would massively improve performance.

while (true)
{
    if(!t1.isAlive)
    {
        t1.Start();
    }
    Thread.Sleep(1000);
}

(You can adjust the time to anything that makes sense in your context.)

Though instead of this multi-thread solution, i would ask: why does thread t1 terminate because of an Exception? You can catch it with a try-catch block.

Instead of UpdateResults call SafeUpdateResults which just says:

void SafeUpdateResults()
{
    while (true)
    {
        try { UpdateResults(); }
        catch (Exception e)
        {
            //track the Error if you want
            Console.WriteLine("t1-Error: " + e.Message);
        }
    }
}

I would even recommend, going into the function UpdateResults() and catching the Exception right where it happens, and then reacting accordingly (though this here is arguably easier).

分享给朋友:
您可能感兴趣的文章:
随机阅读: