Guest User

Untitled

a guest
Jun 23rd, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. class Program
  2. {
  3. private static List<string> _collection = new List<string>();
  4. static void Main(string[] args)
  5. {
  6. ThreadPool.QueueUserWorkItem(new WaitCallback(AddItems), null);
  7. System.Threading.Thread.Sleep(5000);
  8. ThreadPool.QueueUserWorkItem(new WaitCallback(DisplayItems), null);
  9. Console.ReadLine();
  10. }
  11.  
  12. public static void AddItems(object state_)
  13. {
  14. for (int i = 1; i <= 50; i++)
  15. {
  16. _collection.Add(i.ToString());
  17. Console.WriteLine("Adding " + i);
  18. System.Threading.Thread.Sleep(150);
  19. }
  20. }
  21.  
  22. public static void DisplayItems(object state_)
  23. {
  24. // This will not throw an exception
  25. //for (int i = 0; i < _collection.Count; i++)
  26. //{
  27. // Console.WriteLine("Reading " + _collection[i]);
  28. // System.Threading.Thread.Sleep(150);
  29. //}
  30.  
  31. // This will throw an exception
  32. List<string>.Enumerator enumerator = _collection.GetEnumerator();
  33. while (enumerator.MoveNext())
  34. {
  35. string value = enumerator.Current;
  36. System.Threading.Thread.Sleep(150);
  37. Console.WriteLine("Reading " + value);
  38. }
  39. }
  40. }
  41.  
  42. public static void AddItems(object state_)
  43. {
  44. for (int i = 1; i <= 50; i++)
  45. {
  46. _collection.Add(i.ToString());
  47. Console.WriteLine("Adding " + i);
  48. }
  49. }
Add Comment
Please, Sign In to add comment