检查线程是否正常工作 [英] Checking if a thread is working

查看:73
本文介绍了检查线程是否正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习线程,我想知道是否有办法检查线程是否正常工作,就像这样。



I am learning threading and I was wondering if there was a way to check if a thread was working or not, something like this.

If thread1.working then
    thread2.join()
    thread2 = new thread(address of somemethod)
    thread2.start()
else
    thread1.join()
    thread1 = new thread(address of somemethod)
    thread1.start()
end if





我不是在寻找代码,只是关于它如何工作的资源。



I am not looking for code, just resources on how this would work.

推荐答案

这取决于工作的含义。你只能获得一个线程的状态(IsRunning),但是你无法获得它正在执行的代码的状态。



唯一的方法就是这样做将重写您的后台线程正在运行的代码,以提供某种心跳或您父代码可以检查或订阅的其他状态变量或事件。
That depends on what you mean by "working". You can only get the status of a thread (IsRunning), but you cannot get the status of the code it''s executing.

The only way to do that would be to rewrite the code your background thread is running to provide some sort of "heartbeat" or some other status variable or events that your parent code can check or subscribe to.


您的意思是托管线程状态 [ ^ ]?


CPallini回答了你,但是线程的轮询状态是设计错误的标志。



在某些情况下,您需要阻止呼叫 System.Threading.Thread.Join 。调用线程将处于等待状态,在不浪费任何CPU周期的情况下休眠,直到完成唤醒为止。请参阅:

http://msdn.microsoft .com / zh-cn / library / system.threading.thread.join.aspx [ ^ ]。



我看到你已经在尝试 if(working)thread.Join(),但这真是无意义。解释你想要实现的目标,目的。



在其他情况下,线程在完成时通知其他线程是最好的。怎么样?这取决于。请参阅我对解决方案2的评论。



-SA
CPallini answered you, but the polling of the thread for status is a sign of really wrong design.

In some situations, you need a blocking call System.Threading.Thread.Join. The calling thread will be put in wait state, sleeping without wasting any CPU cycles, until awakened by completion. Please see:
http://msdn.microsoft.com/en-us/library/system.threading.thread.join.aspx[^].

I see you already trying "if (working) thread.Join()", but this is pointless, really. Explain what you are trying to achieve, the purpose of it.

In other cases, it''s the best for a thread to notify other threads on completion. How? It depends. Please see my comments to Solution 2.

—SA


这篇关于检查线程是否正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆