问题
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