Stopping only one thread [closed]

こ雲淡風輕ζ 提交于 2019-12-26 05:03:45

问题


I have many threads in my application, how do I stop only one thread from them? If I use Thread.Sleep() it stops the whole application, I just want to stop a single thread. How do I do that? I am using c#.


回答1:


When you are using Thread.Sleep() you are stopping only thread, which called this method. If your main thread (i.e. UI thread) calls Thread.Sleep(), then application freezes (actually other threads continue working, but UI is not refreshed). So, if you want to stop some thread, then:

  • it should not be main thread
  • just call Thread.Sleep() on that thread

Example (assume this code is executed on main thread):

ThreadPool.QueueUserWorkItem(DoSomething);
Thread.Sleep(1000); // this will freeze application

And this is a callback (which is executed on background thread):

static void DoSomething(object state)
{
    Thread.Sleep(5000); // this will not freeze application
}


来源:https://stackoverflow.com/questions/13202902/stopping-only-one-thread

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