gpt4 book ai didi

c# - 多线程异常和处置。为什么 Dispose 没有调用?

转载 作者:行者123 更新时间:2023-11-30 13:50:40 25 4
gpt4 key购买 nike

'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

Lock C:\SomeFodler

Unhandled Exception: System.Exception: Unexpected exception at ExceptionExample.Program.ThreadTwo() in \visual studio 2010\Projects\ExceptionExample\ExceptionExample\Program.cs:line 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()

输出无一异常(exception):

\Visual Studio 2010\Projects\ExceptionExample\ExceptionExample\bin\Debug>ExceptionExample.exe Lock C:\SomeFodler UnLock C:\SomeFodler

最佳答案

未处理的异常强制 CLR 终止进程。 .NET 4.0 的关机行为略有不同,终结器将在报告异常后运行。但在早期版本中没有。

您可以通过为 AppDomain.CurrentDomain.UnhandledException 编写事件处理程序来解决此默认行为。记录或报告异常并调用 Environment.Exit()。这允许终结器线程运行并调用您的 Unlock() 方法。

不要依赖于此,无论如何都会有像 StackOverflow 或 FEEE 这样令人讨厌的异常终止进程。是否有人被电源线绊倒或使用 Taskmgr.exe 击中您的进程

关于c# - 多线程异常和处置。为什么 Dispose 没有调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5777204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com