Stop program when thread finished [duplicate]

丶灬走出姿态 提交于 2019-12-12 06:56:54

问题


I'm a newbie in C#. I have a windows service. In this service, I run a thread. I want to stop the service immediately after the thread finish. Currently, my code is like:

while(true){
     if(isThreadFinished){
          MyService.Stop();
          break;
     }
}

It work, but I feel that using while(true) like that is a stupid way. So, I want to know if there is any other way to achieve my request.


回答1:


And Why don't use the delegate? You have a sample and the documentation here , in the official MSDN website...

You just call you're delegate method before the end of your Thread...

That's more proprely that a while loop... and more optimize if your thread during a long time...




回答2:


bool x=true;
while(x==true){
 if(isThreadFinished){
      x=false;
      MyService.Stop();
      break;
 }
}



回答3:


I don't know C#, but usually you would have an API thread.join() or similar which waits for the thread to finish.

If nothing else you can block on the same synchronised object.

In Java, there's also Object.wait() and Object.notify() that does the trick.



来源:https://stackoverflow.com/questions/18228145/stop-program-when-thread-finished

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!