<p>Consider this problem: I have a program which should fetch (let's say) 100 records from a database, and then for each one it should get updated information from a web service. There are two ways to introduce parallelism in this scenario:</p>

<ol>
<li><p>I start each request to the web service on a new Thread. The number of simultaneous threads is controlled by some external parameter (or dynamically adjusted somehow).</p></li>
<li><p>I create smaller batches (let's say of 10 records each) and launch each batch on a separate thread (so taking our example, 10 threads).</p></li>
</ol>

<p>Which is a better approach, and why do you think so?</p>

[{'answer_id': 10264, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 2, 'selected': False, 'text': "<p>Two things to consider.</p>\n<h3>1. How long will it take to process a record?</h3>\n<p>If record processing is very quick, the overhead of handing off records to threads can become a bottleneck.  In this case, you would want to bundle records so that you don't have to hand them off so often.</p>\n<p>If record processing is reasonably long-running, the difference will be negligible, so the simpler approach (1 record per thread) is probably the best.</p>\n<h3>2. How many threads are you planning on starting?</h3>\n<p>If you aren't using a threadpool, I think you either need to manually limit the number of threads, or you need to break the data into big chunks.  Starting a new thread for every record will leave your system thrashing if the number of records get large.</p>\n"}, {'answer_id': 10291, 'author': 'Hugo', 'author_id': 972, 'author_profile': 'https://Stackoverflow.com/users/972', 'pm_score': 0, 'selected': False, 'text': "<p>The computer running the program is probably not the bottleneck, so:\nRemember that the HTTP protocol has a keep-alive header, that lets you send several GET requests on the same sockets, which saves you from the TCP/IP hand shake. Unfortunately I don't know how to use that in the .net libraries. (Should be possible.)</p>\n\n<p>There will probably also be a delay in answering your requests. You could try making sure that you allways have a given number of outstanding requests to the server.</p>\n"}, {'answer_id': 10296, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Get the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=e848dc1d-5be3-4941-8705-024bc7f180ba" rel="nofollow noreferrer">Parallel Fx</a>.  Look at the BlockingCollection.  Use a thread to feed it batches of records, and 1 to n threads pulling records off the collection to service.  You can control the rate at which the collection is fed, and the number of threads that call to web services.  Make it configurable via a ConfigSection, and make it generic by feeding the collection Action delegates, and you\'ll have a nice little batcher you can reuse to your heart\'s content.</p>\n'}, {'answer_id': 10484, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 4, 'selected': True, 'text': '<p>Option 3 is the best:</p>\n\n<p>Use Async IO.</p>\n\n<p>Unless your request processing is complex and heavy, your program is going to spend 99% of it\'s time waiting for the HTTP requests.</p>\n\n<p>This is exactly what Async IO is designed for - Let the windows networking stack (or .net framework or whatever) worry about all the waiting, and just use a single thread to dispatch and \'pick up\' the results.</p>\n\n<p>Unfortunately the .NET framework makes it a right pain in the ass. It\'s easier if you\'re just using raw sockets or the Win32 api. Here\'s a (tested!) example using C#3 anyway:</p>\n\n<pre><code>using System.Net; // need this somewhere\n\n// need to declare an class so we can cast our state object back out\nclass RequestState {\n    public WebRequest Request { get; set; }\n}\n\nstatic void Main( string[] args ) {\n    // stupid cast neccessary to create the request\n    HttpWebRequest request = WebRequest.Create( "http://www.stackoverflow.com" ) as HttpWebRequest;\n\n    request.BeginGetResponse(\n        /* callback to be invoked when finished */\n        (asyncResult) =&gt; { \n            // fetch the request object out of the AsyncState\n            var state = (RequestState)asyncResult.AsyncState; \n            var webResponse = state.Request.EndGetResponse( asyncResult ) as HttpWebResponse;\n\n            // there we go;\n            Debug.Assert( webResponse.StatusCode == HttpStatusCode.OK ); \n\n            Console.WriteLine( "Got Response from server:" + webResponse.Server );\n        },\n        /* pass the request through to our callback */\n        new RequestState { Request = request }  \n    );\n\n    // blah\n    Console.WriteLine( "Waiting for response. Press a key to quit" );\n    Console.ReadKey();\n}\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>In the case of .NET, the \'completion callback\' actually gets fired in a ThreadPool thread, not in your main thread, so you will still need to lock any shared resources, but it still saves you all the trouble of managing threads.</p>\n'}]
['https://Stackoverflow.com/questions/10229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/380/']