using'语句保证对象将调用Dispose方法。但在这个例子中,这并没有发生。而且终结器方法也没有被调用。
为什么会这样?我该如何更改代码以确保在其他线程出现异常时正确处理对象的释放?
'class Program
{
static void Main(string[] args)
{
Thread th1 = new Thread(ThreadOne);
Thread th2 = new Thread(ThreadTwo);
th1.Start();
th2.Start();
th1.Join();
th2.Join();
}
static void ThreadOne()
{
using (LockedFolder lf = new LockedFolder(@"C:\SomeFodler"))
{
// some pay load
Thread.Sleep(5000);
}
}
static void ThreadTwo()
{
// some pay load
Thread.Sleep(1000);
throw new Exception("Unexpected exception");
}
}
public class LockedFolder : IDisposable
{
private const string FILENAME_LOCK = ".lock-file";
private bool bLocked = false;
public string FullPath { private set; get; }
public LockedFolder(string FullPath)
{
this.FullPath = FullPath;
Lock();
}
private void Lock()
{
// lock our folder
Console.WriteLine("Lock " + FullPath);
//CreateLockFile(Path + FILENAME_LOCK);
bLocked = true;
}
private void UnLock()
{
if (!bLocked)
{
Console.WriteLine("Already UnLocked " + FullPath);
return; // already unlocked
}
Console.WriteLine("UnLock " + FullPath);
// unlock our folder
//DeleteLockFile(Path + FILENAME_LOCK);
bLocked = false;
}
#region IDisposable Members
private bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Free managed resources
}
// Free unmanaged resource
UnLock();
}
disposed = true;
}
~LockedFolder()
{
Dispose(false);
}
#endregion
}
输出:
\Visual Studio 2010\Projects\ExceptionExample\ExceptionExample\bin\Debug>ExceptionExample.exe
锁定 C:\SomeFodler
未处理的异常: System.Exception: 意外的异常 在 \visual studio 2010\Projects\ExceptionExample\ExceptionExample\Program.cs 的 ExceptionExample.Program.ThreadTwo() 中,第 36 行 at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()
没有异常的输出:
\Visual Studio 2010\Projects\ExceptionExample\ExceptionExample\bin\Debug>ExceptionExample.exe 锁定 C:\SomeFodler 解锁 C:\SomeFodler
GC.SuppressFinalize(this);
吗? - bitxwiseUnlock
方法中的文本,所以你的Dispose
方法没有被调用? - bitxwise