Example #1
0
        public void ExclusiveFileAccess()
        {
            // create the test file
            using (StreamWriter writer = new StreamWriter(File.OpenWrite("test.test"))) {
                writer.Write("Hello World!");
                writer.Close();
            }

            // kick off the thread to do the second open
            ManualResetEvent first  = new ManualResetEvent(false);
            ManualResetEvent second = new ManualResetEvent(false);
            ManualResetEvent third  = new ManualResetEvent(false);
            ManualResetEvent fourth = new ManualResetEvent(false);

            Async.Fork(delegate() {
                first.WaitOne();
                try {
                    using (Stream f = StreamUtil.FileOpenExclusive("test.test")) {
                        Assert.IsNull(f, "file open succeeded when it was expected to fail");
                    }
                } catch {
                    third.Set();
                    fourth.Set();
                    throw;
                }
                second.WaitOne();
                third.Set();
                try {
                    using (Stream f = StreamUtil.FileOpenExclusive("test.test")) {
                        Assert.IsNotNull(f, "file open failed when it was expected to succeed");
                    }
                } catch {
                    fourth.Set();
                    throw;
                }
                fourth.Set();
            }, null);

            // open the file first
            using (Stream g = StreamUtil.FileOpenExclusive("test.test")) {
                first.Set();
                Thread.Sleep(2000);
                second.Set();
                Thread.Sleep(500);
                third.WaitOne();
                g.Close();
            }
            fourth.WaitOne();
            File.Delete("test.test");
        }