简体   繁体   中英

running one process after another using multithreading and c#

I use multithreading to process a list of data. In this example below, for each element, how to make sure "SecondProcess" always runs after "FirstProcess" finishes? The order of elements in the queue being processed doesn't really matter.

public class Processor
{
    public void Process()
    {
        IList<int> queue = QueueGenerator.GetRandomInt(50); //gets a list of 50 unique random integer

        foreach (int eachElement in queue)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(FirstProcess), eachElement);
        }
        Console.ReadLine();
    }

    private void FirstProcess(object toProcess)
    {
        int i = 0;
        int.TryParse(toProcess.ToString(), out i);

        string odd = "odd";
        string even = "even";

        string toDisplay = (i%2 == 0)
                               ? string.Format("First step: Processing {0} ({1} number)", i, even)
                               : string.Format("First step: Processing {0} ({1} number)", i, odd);

        Console.WriteLine(toDisplay);
    }

    private void SecondProcess(object toProcess)
    {
        int i = 0;
        int.TryParse(toProcess.ToString(), out i);
        Console.WriteLine("Second step: Processing -> {0}", i);
    }
}

any idea please?

Thanks

If, instead of

foreach (int eachElement in queue)
{
    ThreadPool.QueueUserWorkItem(new WaitCallback(FirstProcess), eachElement);
}

you did

Parallel.ForEach(queue, eachElement => FirstProcess(eachElement));

this will call the delegate for each item in queue in parallel in the ThreadPool , but block until all elements have been processed.

This means that when the next line of code executes on this calling thread, all the work will be complete.

Now, you just do it again:

Parallel.ForEach(queue, eachElement => SecondProcess(eachElement));

Using the Parallel class will have advantages because it can make use of a partitioner, and so, effectively queue batched operations to the ThreadPool rather than queuing individual items into the ThreadPool queue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM