Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 25th, 2012  |  syntax: None  |  size: 0.93 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Determining Thread Safety in Unit Tests
  2. public class MyClass
  3. {
  4.     private List<string> MyList = new List<string>();
  5.  
  6.     public void Add(string Data)
  7.     {
  8.         MyList.Add(Data);  //This is not thread safe!!
  9.     }
  10. }
  11.        
  12. boolean failed = false;
  13. int iterations = 100;
  14.  
  15. // threads interact with some object - either
  16. Thread thread1 = new Thread(new ThreadStart(delegate() {
  17.    for (int i=0; i<iterations; i++) {
  18.      doSomething(); // call unsafe code
  19.      // check that object is not out of synch due to other thread
  20.      if (bad()) {
  21.        failed = true;
  22.      }
  23.    }
  24. });
  25. Thread thread2 = new Thread(new ThreadStart(delegate() {
  26.    for (int i=0; i<iterations; i++) {
  27.      doSomething(); // call unsafe code
  28.      // check that object is not out of synch due to other thread
  29.      if (bad()) {
  30.        failed = true;
  31.      }
  32.    }
  33. });
  34.  
  35. thread1.start();
  36. thread2.start();
  37. thread1.join();
  38. thread2.join();
  39. Assert.IsFalse(failed, "code was thread safe");