TheBulgarianWolf

Threads-Entering The Pool Via TPL

Nov 21st, 2020
721
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.10 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4.  
  5. namespace MoreMethodExercises
  6. {
  7.     class Program
  8.     {
  9.         static void Main()
  10.         {
  11.             // Start the task executing:
  12.             Task<string> task = Task.Factory.StartNew<string>
  13.               (() => DownloadString("http://www.linqpad.net"));
  14.  
  15.             // We can do other work here and it will execute in parallel:
  16.             RunSomeOtherMethod();
  17.  
  18.             // When we need the task's return value, we query its Result property:
  19.             // If it's still executing, the current thread will now block (wait)
  20.             // until the task finishes:
  21.             string result = task.Result;
  22.         }
  23.  
  24.         private static void RunSomeOtherMethod()
  25.         {
  26.             for(int i = 0; i < 10; i++)
  27.             {
  28.                 Console.WriteLine(i);
  29.                 Thread.Sleep(1000);
  30.             }
  31.         }
  32.  
  33.         static string DownloadString(string uri)
  34.         {
  35.             using (var wc = new System.Net.WebClient())
  36.                 return wc.DownloadString(uri);
  37.         }
  38.  
  39.     }
  40. }
  41.  
Add Comment
Please, Sign In to add comment