我有一个 Windows 窗体应用程序,它本身会启动不同的线程来完成不同类型的工作。有时,所有线程(包括 UI 线程)都被冻结,我的应用程序变得无响应。我认为这可能是与垃圾收集器相关的问题,因为 GC 将暂时冻结所有托管线程。为了验证只是托管线程被冻结,我启动了一个非托管线程,它每秒写入一个带有时间戳的“心跳”文件,并且它不受影响(即它仍然运行):
public delegate void ThreadProc();
[DllImport("UnmanagedTest.dll", EntryPoint = "MyUnmanagedFunction")]
public static extern void MyUnmanagedFunction();
[DllImport("kernel32")]
public static extern IntPtr CreateThread(
IntPtr lpThreadAttributes,
uint dwStackSize,
IntPtr lpStartAddress,
IntPtr lpParameter,
uint dwCreationFlags,
out uint dwThreadId);
uint threadId;
ThreadProc proc = new ThreadProc(MyUnmanagedFunction);
IntPtr functionPointer = Marshal.GetFunctionPointerForDelegate(proc);
IntPtr threadHandle = CreateThread(IntPtr.Zero, 0, functionPointer, IntPtr.Zero, 0, out threadId);
我的问题是:如何模拟这种情况,所有托管线程都被挂起但非托管线程继续旋转?
我的第一次刺:
private void button1_Click(object sender, EventArgs e) {
Thread t = new Thread(new ThreadStart(delegate {
new Hanger();
GC.Collect(2, GCCollectionMode.Forced);
}));
t.Start();
}
class Hanger{
private int[] m_Integers = new int[10000000];
public Hanger() { }
~Hanger() { Console.WriteLine("About to hang...");
//This doesn't reproduce the desired behavior
//while (true) ;
//Neither does this
//Thread.Sleep(System.Threading.Timeout.Infinite);
}
}
提前致谢!!