Note that there are some explanatory texts on larger screens.

plurals
  1. POasync / await - am I correctly running these methods in parallel?
    text
    copied!<p>I have an abstract class called <code>VehicleInfoFetcher</code> which returns information asynchronously from a <code>WebClient</code> via this method:</p> <pre><code>public override async Task&lt;DTOrealtimeinfo&gt; getVehicleInfo(string stopID); </code></pre> <p>I'd like to combine the results of two separate instances of this class, running each in parallel before combining the results. This is done within a third class, <code>CombinedVehicleInfoFetcher</code> (also itself a subclass of <code>VehicleInfoFetcher</code>)</p> <p>Here's my code - but I'm not quite convinced that it's running the tasks in parallel; am I doing it right? Could it be optimized?</p> <pre><code> public class CombinedVehicleInfoFetcher : VehicleInfoFetcher { public HashSet&lt;VehicleInfoFetcher&gt; VehicleInfoFetchers { get; set; } public override async Task&lt;DTOrealtimeinfo&gt; getVehicleInfo(string stopID) { // Create a list of parallel tasks to run var resultTasks = new List&lt;Task&lt;DTOrealtimeinfo&gt;&gt;(); foreach (VehicleInfoFetcher fetcher in VehicleInfoFetchers) resultTasks.Add(fetcher.getVehicleInfo(stopID, stopID2, timePointLocal)); // run each task foreach (var task in resultTasks) await task; // Wait for all the results to come in await Task.WhenAll(resultTasks.ToArray()); // combine the results var allRealtimeResults = new List&lt;DTOrealtimeinfo&gt;( resultTasks.Select(t =&gt; t.Result) ); return combineTaskResults(allRealtimeResults); } DTOrealtimeinfo combineTaskResults(List&lt;DTOrealtimeinfo&gt; realtimeResults) { // ... return rtInfoOutput; } } </code></pre> <p><strong>Edit</strong> </p> <p>Some very helpful answers, here is a re-written example to aid discussion with usr below:</p> <pre><code> public override async Task&lt;object&gt; combineResults() { // Create a list of parallel tasks to run var resultTasks= new List&lt;object&gt;(); foreach (AnotherClass cls in this.OtherClasses) resultTasks.Add(cls.getResults() ); // Point A - have the cls.getResults() methods been called yet? // Wait for all the results to come in await Task.WhenAll(resultTasks.ToArray()); // combine the results return new List&lt;object&gt;( resultTasks.Select(t =&gt; t.Result) ); } } </code></pre>
 

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