Guest User

Untitled

a guest
Oct 19th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. static class Bar {
  2. public static string MightThrowException(int i) {
  3. if (i == 2) throw new Exception("bad error: " + i.ToString());
  4. // if not 2, just return input
  5. return i.ToString();
  6. }
  7. }
  8.  
  9. public async Task<string> TestThrottle() {
  10. var tasks = new List<Task<string>>();
  11. var results = new List<string>();
  12.  
  13. // mock the 'priming' that occurs in a throttling pattern
  14. tasks.Add(Task.Run(() => Bar.MightThrowException(0)));
  15.  
  16. // begin throttling, for an additional 4 tasks
  17. for (var i = 1; i < 5; i++) {
  18. try {
  19. var task = await Task.WhenAny(tasks);
  20. results.Add(task.Result);
  21. tasks.Remove(task);
  22. }
  23. catch (Exception ex) {
  24. results.Add("handled " + ex.Message);
  25. }
  26. tasks.Add(Task.Run(() => Bar.MightThrowException(i)));
  27. }
  28.  
  29. return string.Join("n", results);
  30. }
  31.  
  32. Task.Run(() => {
  33. string result = new Foo().TestThrottle().Result;
  34. System.Diagnostics.Debug.WriteLine(result);
  35. }).Wait();
  36.  
  37. tasks.Add(Task.Run(() => Bar.MightThrowException(i)));
Add Comment
Please, Sign In to add comment