Note that there are some explanatory texts on larger screens.

plurals
  1. POC# async and tasks
    text
    copied!<p>I have a function that sends requests to search for information from a url. The search criteria is a list and the search iterates through each item and requests info from the url. To speed it up I divide the list into x subsets, and create a task for each subset. Then each subset sends 3 simultaneous requests, as follows:</p> <p>This is the main entry point:</p> <pre><code>Search search = new Search(); await Task.Run(() =&gt; search.Start()); </code></pre> <p>The Start function:</p> <pre><code>public void Search() { //Each subset is a List&lt;T&gt; ie where T is certain search criteria //If originalList.Count = 30 and max items per subset is 10, then subsets will be 3 lists of 10 items each var subsets = CreateSubsets(originalList); List&lt;Task&gt; tasks = new List&lt;Task&gt;(subsets.Count); for (int i = 0; i &lt; subsets.Count; i++) tasks.Add(Task.Factory.StartNew(() =&gt; SearchSubset(subsets[i])); Task.WaitAll(tasks.ToArray()); foreach (Task task in tasks) if (task != null) task.Dispose(); } private void SearchSubset(List&lt;SearchCriteria&gt; subset) { //Checking that i+1 and i+2 is within subset.Count-1 has been omitted for (int i = 0; i &lt; subset.Count; i+=3) { Task[] tasks = {Task.Factory.StartNew(() =&gt; SearchCriteria(subset[i])), Task.Factory.StartNew(() =&gt; SearchCriteria(subset[i+1])), Task.Factory.StartNew(() =&gt; SearchCriteria(subset[i+2]))}; //Wait &amp; dispose like above } } private void SearchCriteria(SearchCriteria criteria) { //SearchForCriteria uses WebRequest and WebResponse (callback) //to query the url and return the response.content var results = SearchForCriteria(criteria); //process results... } </code></pre> <p>The above code works fine and the search is quite fast. However, does the above code create too much overhead, and is there is more cleaner (or simpler) way to achieve the same results?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload