Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6114167
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T14:56:35+00:00 2026-05-23T14:56:35+00:00

I have some work (a job) that is in a queue (so there a

  • 0

I have some work (a job) that is in a queue (so there a several of them) and I want each job to be processed by a thread.

I was looking at Rx but this is not what I wanted and then came across the parallel task library.

Since my work will be done in an web application I do not want client to be waiting for each job to be finished, so I have done the following:

    public void FromWebClientRequest(int[] ids);
    {
        // I will get the objects for the ids from a repository using a container (UNITY)


       ThreadPool.QueueUserWorkItem(delegate
                                         {
                                             DoSomeWorkInParallel(ids, container);
                                         });
    }

    private static void DoSomeWorkInParallel(int[] ids, container)
    {
        Parallel.ForEach(ids, id=>
                                        {
                                            Some work will be done here...
                                            var respository = container.Resolve...
                                        });


       // Here all the work will be done.
       container.Resolve<ILogger>().Log("finished all work");
    }

I would call the above code on a web request and then the client will not have to wait.

Is this the correct way to do this?

TIA

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T14:56:36+00:00Added an answer on May 23, 2026 at 2:56 pm

    From the MSDN docs I see that Unitys IContainer Resolve method is not thread safe (or it is not written). This would mean that you need to do that out of the thread loop. Edit: changed to Task.

    public void FromWebClientRequest(int[] ids);
    {
       IRepoType repoType = container.Resolve<IRepoType>();
       ILogger logger = container.Resolve<ILogger>();
       // remove LongRunning if your operations are not blocking (Ie. read file or download file  long running queries etc)
       // prefer fairness is here to try to complete first the requests that came first, so client are more likely to be able to be served "first come, first served" in case of high CPU use with lot of requests
       Task.Factory.StartNew(() => DoSomeWorkInParallel(ids, repoType, logger), TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness);
    }
    
    private static void DoSomeWorkInParallel(int[] ids, IRepoType repository, ILogger logger)
    {
        // if there are blocking operations inside this loop you ought to convert it to tasks with LongRunning
        // why this? to force more threads as usually would be used to run the loop, and try to saturate cpu use, which would be doing nothing most of the time
        // beware of doing this if you work on a non clustered database, since you can saturate it and have a bottleneck there, you should try and see how it handles your workload
        Parallel.ForEach(ids, id=>{
                      // Some work will be done here...
                      // use repository
                 });
       logger.Log("finished all work");
    }
    

    Plus as fiver stated, if you have .Net 4 then Tasks is the way to go.

    Why go Task (question in comment):

    If your method fromClientRequest would be fired insanely often, you would fill the thread pool, and overall system performance would probably not be as good as with .Net 4 with fine graining. This is where Task enters the game. Each task is not its own thread but the new .Net 4 thread pool creates enough threads to maximize performance on a system, and you do not need to bother on how many cpus and how much thread context switches would there be.

    Some MSDN quotes for ThreadPool:

    When all thread pool threads have been
    assigned to tasks, the thread pool
    does not immediately begin creating
    new idle threads. To avoid
    unnecessarily allocating stack space
    for threads, it creates new idle
    threads at intervals. The interval is
    currently half a second, although it
    could change in future versions of the
    .NET Framework.

    The thread pool has a default size of
    250 worker threads per available
    processor

    Unnecessarily increasing the number of
    idle threads can also cause
    performance problems. Stack space must
    be allocated for each thread. If too
    many tasks start at the same time, all
    of them might appear to be slow.
    Finding the right balance is a
    performance-tuning issue.

    By using Tasks you discard those issues.

    Another good thing is you can fine grain the type of operation to run. This is important if your tasks do run blocking operations. This is a case where more threads are to be allocated concurrently since they would mostly wait. ThreadPool cannot achieve this automagically:

    Task.Factory.StartNew(() => DoSomeWork(), TaskCreationOptions.LongRunning);
    

    And of course you are able to make it finish on demand without resorting to ManualResetEvent:

    var task = Task.Factory.StartNew(() => DoSomeWork());
    task.Wait();
    

    Beside this you don’t have to change the Parallel.ForEach if you don’t expect exceptions or blocking, since it is part of the .Net 4 Task Parallel Library, and (often) works well and optimized on the .Net 4 pool as Tasks do.

    However if you do go to Tasks instead of parallel for, remove the LongRunning from the caller Task, since Parallel.For is a blocking operations and Starting tasks (with the fiver loop) is not. But this way you loose the kinda first-come-first-served optimization, or you have to do it on a lot more Tasks (all spawned through ids) which probably would give less correct behaviour. Another option is to wait on all tasks at the end of DoSomeWorkInParallel.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have some tabs using jQuery UI which work just fine, but I want
I have some code that essentially does what I want but I always like
I have some AJAX work that brings across an additional form element that I
I have done some work with Ruby on Rails but am still not comfortable
I'm onto problem 245 now but have hit some problems. I've done some work
I have to do some work work with integers, but I am interested in
I have some CSS style that does not work in IE and that works
I currently have a MapReduce job that uses MultipleOutputs to send data to several
I have some workflow to work with in Worflow foundation. I need to follow
I have some experience in ASP.Net and can work my way around it without

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.