public static async System.Threading.Tasks.Task DoSomething() { int rnd = random.Value.Next(0, 200); await System.Threading.Tasks.Task.Delay(rnd); if (rnd % 2 == 0) { await ThreadSafetyTest.AsyncDoSomething1(); } else { await ThreadSafetyTest.AsyncDoSomething2(); } }
public static void Test() { bool failed = false; int iterations = 100; // threads interact with some object - either System.Threading.Thread thread1 = new System.Threading.Thread( new System.Threading.ThreadStart( delegate () { for (int i = 0; i < iterations; i++) { ThreadSafetyTest.DoSomething1(); // call unsafe code // check that object is not out of synch due to other thread if (IsBad()) { failed = true; } } }) ); System.Threading.Thread thread2 = new System.Threading.Thread( new System.Threading.ThreadStart( delegate () { for (int i = 0; i < iterations; i++) { ThreadSafetyTest.DoSomething2(); // call unsafe code // check that object is not out of synch due to other thread if (IsBad()) { failed = true; } } }) ); thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join(); System.Diagnostics.Debug.Assert(failed == false, "The code was thread safe"); }