線程對文件沒有鎖定(至少不像操作系統那樣)。考慮下面的例子。線程t
創建一個文件並鎖定該文件。主線程寫入流並關閉它。這表明該線程不擁有該鎖。該過程確實如此。
Stream stream = null;
Thread t = new Thread(() => stream = File.OpenWrite (@"c:\temp\junk111.txt"));
t.Start();
Thread.Sleep(1000);
Console.WriteLine(t.ThreadState);
stream.WriteByte(89);
stream.Close();
File.OpenWrite (@"c:\temp\junk222.txt");
打印stopped
,以便打開該文件不運行了,但該文件處理它創建線程仍處於打開狀態。
這裏的FxCop的結果對上述文件
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop>FxCopCmd.exe /file:c:\code\jeremy.sellars\test\Junk\bin\Debug\Junk.exe /console
Microsoft (R) FxCop Command-Line Tool, Version 10.0 (10.0.30319.1) X86
Copyright (C) Microsoft Corporation, All Rights Reserved.
...
[Location not stored in Pdb] : warning : CA2210 : Microsoft.Design : Sign 'Junk.exe' with a strong name key.
C:\code\jeremy.sellars\TEST\Junk\Program.cs(50,1) : warning : CA2000 : Microsoft.Reliability : In method 'Program.Main()', call System.IDisposable.Dispose on object 'File.OpenWrite("c:\\temp\\junk2.txt")' before all references to it are out of scope.
Done:00:00:06.1251568
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop>
如果您在VisualStudio的異常捕獲,然後打開「線程」視圖('調試相關部分|視窗| Threads',從主菜單),那麼它應該在當前線程旁邊顯示一個黃色箭頭,該箭頭應該與發生異常的那個線程相同。 – CodingWithSpike 2011-06-14 19:48:53
是的,我可以。我可能不得不訴諸於此,這可能會很費力,因爲當時可能有多個線程正在運行。 – 2011-06-14 20:23:34
我聽說FxCop(在編譯時)可以在代碼中發現一些一次性問題。你有沒有考慮過這個? – 2011-06-14 20:29:42