Guest User

Untitled

a guest
Aug 17th, 2016
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.36 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4.  
  5. namespace Taski
  6. {
  7.     class Program
  8.     {
  9.         private static Random r = new Random();
  10.         static void Main(string[] args)
  11.         {
  12.             //zamiast listy zwykłych stringów potrzebujemy listę Tasków, żeby async ... await mogło zadziałać
  13.             List<Task<string>> results = new List<Task<string>>();
  14.             for (int i = 0; i < 20; i++)
  15.             {
  16.                 //odpalamy asynchroniczne zadania (żeby w tle już sobie działały)
  17.                 //kod wygląda na zwykły synchroniczny kod, zwracamy taska z metody asynchronicznej, który kiedyś da nam jakiś rezultat
  18.                 results.Add(GetAsync(i));
  19.             }
  20.  
  21.             //równoległa wersja pętli for - jeśli zależy nam na kolejności to zastępujemy zwykłym
  22.             Parallel.ForEach(results,
  23.                 //lambda musi być asynchroniczna bo będziemy czekać na wynik
  24.                 async msg =>
  25.             {
  26.                 //zanim wypiszemy musimy poczekać na wynik
  27.                 Console.WriteLine(await msg);
  28.             });
  29.             Console.ReadKey();
  30.         }
  31.  
  32.         private static async Task<string> GetAsync(int x)
  33.         {
  34.             await Task.Delay(r.Next(300, 3000));
  35.             return x + " returned value!";
  36.         }
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment