ThreadPool.QueueUserWorkItem - order not saved?

I just noticed that the order of the callbacks queued through ThreadPool.QueueUserWorkItem

is not deterministic, it is definitely not the order in which the callbacks were passed through.

This can be verified with the following simple program:

    private static void Main()
    {
        for (var i = 0; i < 10; ++i)
            ThreadPool.QueueUserWorkItem(Console.Write, i + " ");

        Thread.Sleep(1000);
    }

      

Single run output:

0 3 8 9 1 2 5 4 6 7

      

The name implies the preservation of order.

Is there a way to make sure the order is preserved?
If not, what alternative implementation do you suggest?

+3


source to share


4 answers


If you want tasks to run sequentially, but on a different thread than the calling thread, you should look at EventLoopScheduler in Reactive Extensions . It allows you to schedule units of work for a specific workflow.



+4


source


Unable to save order. The purpose of a thread pool is to run independent tasks in parallel. The order in which these tasks begin and end is inherently highly non-deterministic. If you need subtasks to start and finish in a specific order, you cannot parallelize them.

private static void Main()
{
    for (var i = 0; i < 10; ++i)
        Console.Write(i + " ");

    Thread.Sleep(1000);
}

      



To clarify, the order of tasks in the thread pool queue is preserved, but the order in which they are actually executed is non-deterministic.

+5


source


I'm not sure if the startup order of the tasks is saved or not. But, since all delivered work items are executed asynchronously, you cannot guarantee the execution order in any case.

If you want to save the order, one option is to run work items one at a time rather than from a thread pool. Another is to schedule a second job inside the first, etc. Another is to use wait mechanisms to synchronize work.

+2


source


The name implies the preservation of order.

"queue" in the name means that items are queued for execution on the threads in the thread pool .. which means if all but one of the threads in the thread pool were busy, then your objects will be queued in turn in that order in which you put them. but as it is unlikely that items are collected on the first available background thread and then executed concurrently.

+1


source







All Articles