0

My situation is that i am creating multiple threads for performing a job. For instance you can say that "Job is to process some data." Now as soon as the user press "Stop" button, i want to abort all these threads and update the status of job in database.

    internal void CreateJobThread(Job job)
    {
        Interlocked.Increment(ref _threadCounter);
        ThreadPool.QueueUserWorkItem(StartJobThread, job);
    }

StartJobThread is the function which is doing job.

    internal void StartJobThread(object input)
    {
        try
        {
            //Do something
        }
        catch (Exception ex)
        {
            //Catch exception
        }
        finally
        {
            Interlocked.Decrement(ref _threadCounter);
        }
    }

Please let me know how can i cancel all of the threads currently running. And how can i get the IDs of jobs in progress. So that i can update their status in database.

meriaz
  • 65
  • 1
  • 11
  • It's not correct to think that `ThreadPool.QueueUserWorkItem()` is _"creating ...threads"_ directly in all cases, rather it queues a job to be performed later by an already created _thread pool_ thread. That thread can handle multiple jobs in series. _[Queues a method for execution. The method executes when a thread pool thread becomes available.](https://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem(v=vs.110).aspx)_. A thread _may_ be created (thus increasing the size of the thread pool) depending on the number of pending jobs. –  Nov 02 '15 at 05:23
  • 1
    You should not Abort threads in general and especially not those in the pool. Look into Task and CamcelationTokens – H H Nov 02 '15 at 05:52

0 Answers0