Let’s play a little game of “Spot the Defect”. For the following code, see if you can:
- Figure out what it would output
- Find the bug(s)
- Correct the bugs
(And I’ll do a post next week with the answer)
using System; using System.Threading; namespace SpotTheDefect1 { class Program { private static int _x = 0; private static Foo _foo = new Foo(); private static bool _disposed = false; static void Main(string[] args) { Thread thread1 = new Thread(Thread1); Thread thread2 = new Thread(Thread2); thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join(); } private static void Thread1() { if (!_disposed) { _foo.Bar(); } } private static void Thread2() { Console.WriteLine("Disposing"); _disposed = true; _foo = null; } private class Foo { public void Bar() { Console.WriteLine("Hello, World!"); } } } }
Advertisement