Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Threading.Tasks;
- namespace Taski
- {
- class Program
- {
- private static Random r = new Random();
- static void Main(string[] args)
- {
- //zamiast listy zwykłych stringów potrzebujemy listę Tasków, żeby async ... await mogło zadziałać
- List<Task<string>> results = new List<Task<string>>();
- for (int i = 0; i < 20; i++)
- {
- //odpalamy asynchroniczne zadania (żeby w tle już sobie działały)
- //kod wygląda na zwykły synchroniczny kod, zwracamy taska z metody asynchronicznej, który kiedyś da nam jakiś rezultat
- results.Add(GetAsync(i));
- }
- //równoległa wersja pętli for - jeśli zależy nam na kolejności to zastępujemy zwykłym
- Parallel.ForEach(results,
- //lambda musi być asynchroniczna bo będziemy czekać na wynik
- async msg =>
- {
- //zanim wypiszemy musimy poczekać na wynik
- Console.WriteLine(await msg);
- });
- Console.ReadKey();
- }
- private static async Task<string> GetAsync(int x)
- {
- await Task.Delay(r.Next(300, 3000));
- return x + " returned value!";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment