public void GetLineCountTest() { MonitorTestSetUp(); const int numLines = 10; var monitor = new TestMonitor(TestHelper.CreateOptions(), WriteToFile, new CancellationToken()); AddAFile(numLines); Assert.AreEqual(2, AddedFiles.Count); Assert.AreEqual(numLines, monitor.GetLineCountPassThru(AddedFiles[1]).Result); var cts = new CancellationTokenSource(); // lock the file on another task Task.Run(() => { using (File.Open(AddedFiles[1], FileMode.Open, FileAccess.ReadWrite)) { } }, cts.Token); // task that waits for GetLines to return var t = Task.Factory.StartNew(async() => { Assert.AreEqual(numLines, await monitor.GetLineCountPassThru(AddedFiles[1])); }); // sleep the test thread for a second just for fun Thread.Sleep(1000); // now cancel the file locking task and the GetLines should proceed cts.Cancel(false); t.Wait(); MonitorTestCleanUp(); }