SanSYS

C# async/await

Jan 28th, 2015
400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.17 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.Net;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6.  
  7. namespace TestAcync
  8. {
  9.     class Program
  10.     {
  11.         class Foo
  12.         {
  13.             public async void Do()
  14.             {
  15.                 Console.WriteLine("Enter your name: ");
  16.  
  17.                 string name = Console.ReadLine();
  18.  
  19.                 Stopwatch sw = Stopwatch.StartNew();
  20.  
  21.                 string s = await AsyncHello(name);
  22.  
  23.                 sw.Stop();
  24.  
  25.                 Console.WriteLine(string.Format("{0}, Ellapsed {1} ms", s, sw.ElapsedMilliseconds));
  26.  
  27.                 Console.ReadKey();
  28.             }
  29.  
  30.             public Task<string> AsyncHello(string name)
  31.             {
  32.                 var task = new Task<string>(() =>
  33.                 {
  34.                     Thread.Sleep(5000);
  35.                    
  36.                     return string.Format("Hi, {0}", name);
  37.                 });
  38.  
  39.                 task.Start();
  40.  
  41.                 return task;
  42.             }
  43.         }
  44.  
  45.         static void Main(string[] args)
  46.         {
  47.             var foo = new Foo();
  48.  
  49.             foo.Do();
  50.  
  51.             Console.ReadKey();
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment