Stas_P

Compile, run, wait for 10 seconds and try to kill me

Feb 21st, 2013
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.46 KB | None | 0 0
  1. internal class Program
  2.     {
  3.         private const int totalRequests = 800;
  4.  
  5.         private static void Main(string[] args)
  6.         {
  7.             var cancellationTockenSource = new CancellationTokenSource();
  8.             LoadTest(cancellationTockenSource);
  9.  
  10.  
  11.             Console.WriteLine("Press any key to break");
  12.             Console.ReadLine();
  13.             cancellationTockenSource.Cancel();
  14.         }
  15.  
  16.         private static async Task LoadTest(CancellationTokenSource cancellationTockenSource)
  17.         {
  18.             Stopwatch stopWatch = Stopwatch.StartNew();
  19.             var requests = new List<Task>(totalRequests);
  20.  
  21.             for (int i = 0; i < totalRequests; ++i)
  22.             {
  23.                 requests.Add(Request(cancellationTockenSource.Token));
  24.             }
  25.             try
  26.             {
  27.                 await Task.WhenAll(requests);
  28.             }
  29.             catch (Exception e)
  30.             {
  31.                 Console.WriteLine(e);
  32.             }
  33.  
  34.             stopWatch.Stop();
  35.             Console.WriteLine(string.Format("{0} req/sec", stopWatch.Elapsed.TotalSeconds/totalRequests));
  36.         }
  37.  
  38.         private static HttpRequestMessage CreateMessage()
  39.         {
  40.             var url = new Uri("http://ya.ru:8080/x");
  41.             var message = new HttpRequestMessage(HttpMethod.Get, url);
  42.             message.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
  43.             return message;
  44.         }
  45.  
  46.         protected static async Task<string> Request(CancellationToken token)
  47.         {
  48.             using (var client = new HttpClient())
  49.             {
  50.                 HttpResponseMessage response = await client.SendAsync(CreateMessage(), token);
  51.                 string content = await response.Content.ReadAsStringAsync();
  52.                 return content;
  53.             }
  54.         }
  55.     }
Advertisement
Add Comment
Please, Sign In to add comment