Search code examples
c#multithreadingthread-safetythreadpoolthread-sleep

Stopping only one thread


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#.


Solution

  • 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
    }