0
IMongoCollection<JobInfoRecord> records = ...
foreach (var record in records.Find(query).ToListAsync().Result)
{...}

Is it true that foreach iteration I compute .Result value again and again?

Muhammad Omer
  • 111
  • 2
  • 14
  • 1
    There is really no benefit to use the `Async` version of the `ToList` if you just call `.Result` on it. You should `await` it. – Magnus Mar 17 '16 at 11:44
  • Can you explain why? –  Mar 17 '16 at 11:45
  • 1
    @ivan_petrushenko Because the point of asynchronous methods it to not block the thread, but by calling `Result` you are blocking the thread. But since you want to iterate the results in your `foreach` there not much point in calling `ToListAsync` either. – juharr Mar 17 '16 at 11:46
  • But what should I calling instead of `.ToListAsync`? –  Mar 17 '16 at 12:10
  • There is no other method to get the `Result`, just `.ToListAsync().Result` –  Mar 17 '16 at 12:19
  • 1
    If the result of Find is Enumerable just do: `foreach (var record in records.Find(query)` – Magnus Mar 17 '16 at 12:27
  • 1
    You might want to try `foreach(var record in await records.FindAsync(query))` – juharr Mar 17 '16 at 13:02

1 Answers1

1

No, it's going to evaluate records.Find(query).ToListAsync().Result once and then call GetEnumerator on the result. Then each loop is going to call MoveNext on the returned "Enumerator" and set record to the Current property of that "Enumerator" with the loop breaking when MoveNext returns false.

juharr
  • 31,741
  • 4
  • 58
  • 93