C# winform卡死问题分析1——线程池子线程创建句柄

最近遇到一个winform上位机程序卡死的问题,排查了半天发现挺有趣,我们一起来分析排查下。

前排提示

生产代码由于各种历史问题出现奇奇怪怪的代码很正常,我们不讨论这段代码该不该这么写,只复盘这样写为什么有问题。

现象

软件打开一个form窗口做了一些操作关闭后,整个软件就卡住了,有时候软件可以自动恢复,有时候一直卡在那里没办法恢复只能重启。

从这个现象里我们抓重点,对于winform来说界面卡住肯定是UI线程阻塞住了,如果卡住偶发一段时间能够恢复,大概率和线程池子线程操作控件相关。

简化Demo代码

从以下代码我们还原当时的操作逻辑是先点击btn1打开窗口1,然后关闭窗口1后点击btn2,然后程序就卡死了。大家也可以在这里看下代码为什么卡死,又为什么偶发能够恢复正常。

//主窗口
public partial class Form1 : Form
{
    TestForm testForm;
    public Form1()
    {
        InitializeComponent();
        testForm = new TestForm();
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        testForm.ShowDialog();
    }

    private async void button2_Click(object sender, System.EventArgs e)
    {
        await Task.Run(() =>
        {
            testForm.Process();
        });
        testForm.ShowMessage("Process success.");
    }
}

//窗口1
public partial class TestForm : Form
{
    public TestForm()
    {
        InitializeComponent();
    }

    //这是一个测试方法
    public void Process()
    {
        TestForm1 testForm1 = new TestForm1();
        testForm1.ShowDialog(this);
    }

    public void ShowMessage(string message)
    {
        this.Invoke((Action)(() =>
        {
            label1.Text = message;
        }));
    }
}

//窗口2
public partial class TestForm1 : Form
{
    public TestForm1()
    {
        InitializeComponent();
    }
}

排查

观察下主线程卡在哪里

我们的代码
6e4bc1b8-484b-49e4-9f5e-ed8543199851
继续反编译代码找到底层卡住的地方
框架代码
5c11ae25-6d3c-4e8d-95ca-5356a9cd3de3
这一步不看不要紧,一看不对啊,我们的TestForm不是在主线程上创建的吗,怎么主线程调用ShowMessage这个函数还需要去跨线程调用呢,这个线程id 4348又是哪里来的呢。因为我们的代码比较简单,很多聪明的同学都猜到了这个线程应该就是我们Task.run的子线程。为什么我们的TestForm这个窗口所属的线程变成了这个线程池的id。

查看控件所属线程框架逻辑

查看Control类发现所属线程id绑定的是窗口句柄,那么查看窗口句柄什么时候发生变化

internal int CreateThreadId
{
	get
	{
		int lpdwProcessId;
		if (IsHandleCreated)
		{
			return SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, Handle), out lpdwProcessId);
		}
		return SafeNativeMethods.GetCurrentThreadId();
	}
}

查看句柄是什么时候销毁的,又是什么时候新建,然后绑定到子线程的
在窗口的句柄创建和句柄销毁的地方打上断点
8af97074-1068-4f45-a334-5d5ef2b357b3
b8b86cf2-0ee4-4825-bfc8-f2109162751a

发现在show窗口2的时候触发了窗口1的句柄重新创建
082e1057-dc2c-4774-822b-0b1bb1e2c5d5
c1be0cbc-b270-4baa-bb82-d9cc904a1bd2

window.CreateHandle(createParams);

这一段代码是将当前线程和句柄进行绑定,最终调用的 Win32 API CreateWindowEx 在操作系统层面完成。

为什么卡死

窗口1的句柄变化已经找到了,并且窗口所属线程变成子线程也已经从代码排查到问题所在。那么为什么卡死,为什么偶尔卡死一段时间后可以自己恢复。

排查代码

回到最开始主线程卡住的位置,我们可以判断到主线程在等待窗口1的回复,但是一直没有回复,所以在循环等待。
我们截一下框架主要处理跨线程调用的方法
主要在这里来判断当前调用线程和控件所属线程是否一致,不一致即flag = false会发送消息到目标控件

if (SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, Handle), out var _) == SafeNativeMethods.GetCurrentThreadId() && synchronous)
	{
		flag = true;
	}
	if (flag)
	{
		InvokeMarshaledCallbacks();
	}
	else
	{
		UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), threadCallbackMessage, IntPtr.Zero, IntPtr.Zero);
	}
private object MarshaledInvoke(Control caller, Delegate method, object[] args, bool synchronous)
{
	if (!IsHandleCreated)
	{
		throw new InvalidOperationException(SR.GetString("ErrorNoMarshalingThread"));
	}
	ActiveXImpl activeXImpl = (ActiveXImpl)Properties.GetObject(PropActiveXImpl);
	if (activeXImpl != null)
	{
		IntSecurity.UnmanagedCode.Demand();
	}
	bool flag = false;
	if (SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, Handle), out var _) == SafeNativeMethods.GetCurrentThreadId() && synchronous)
	{
		flag = true;
	}
	ExecutionContext executionContext = null;
	if (!flag)
	{
		executionContext = ExecutionContext.Capture();
	}
	ThreadMethodEntry threadMethodEntry = new ThreadMethodEntry(caller, this, method, args, synchronous, executionContext);
	lock (this)
	{
		if (threadCallbackList == null)
		{
			threadCallbackList = new Queue();
		}
	}
	lock (threadCallbackList)
	{
		if (threadCallbackMessage == 0)
		{
			threadCallbackMessage = SafeNativeMethods.RegisterWindowMessage(Application.WindowMessagesVersion + "_ThreadCallbackMessage");
		}
		threadCallbackList.Enqueue(threadMethodEntry);
	}
	if (flag)
	{
		InvokeMarshaledCallbacks();
	}
	else
	{
		UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), threadCallbackMessage, IntPtr.Zero, IntPtr.Zero);
	}
	if (synchronous)
	{
		if (!threadMethodEntry.IsCompleted)
		{
			WaitForWaitHandle(threadMethodEntry.AsyncWaitHandle);
		}
		if (threadMethodEntry.exception != null)
		{
			throw threadMethodEntry.exception;
		}
		return threadMethodEntry.retVal;
	}
	return threadMethodEntry;
}

由于子线程没有消息泵没办法处理消息,所以UI消息一直没有complete导致主线程一直在等待。

卡死偶发能够恢复

偶发能够恢复正常我们直接查看等待的那段代码

while (!flag)
{
	flag2 = UnsafeNativeMethods.GetExitCodeThread(handle, out lpExitCode);
	if ((flag2 && lpExitCode != 259) || (!flag2 && Marshal.GetLastWin32Error() == 6) || AppDomain.CurrentDomain.IsFinalizingForUnload())
	{
		if (!waitHandle.WaitOne(1, exitContext: false))
		{
			throw new InvalidAsynchronousStateException(SR.GetString("ThreadNoLongerValid"));
		}
		break;
	}
	if (IsDisposed && threadCallbackList != null && threadCallbackList.Count > 0)
	{
		lock (threadCallbackList)
		{
			Exception exception = new ObjectDisposedException(GetType().Name);
			while (threadCallbackList.Count > 0)
			{
				ThreadMethodEntry threadMethodEntry = (ThreadMethodEntry)threadCallbackList.Dequeue();
				threadMethodEntry.exception = exception;
				threadMethodEntry.Complete();
			}
		}
	}
	flag = waitHandle.WaitOne(1000, exitContext: false);
}

我们可以看到如下代码,如果目标线程状态不等于259,即不是处于存活的状态那么会抛出异常然后结束等待,所以到这里大家也知道为什么卡死偶发恢复了,因为线程池线程空闲一段时间会被回收,所以这里直接走异常流程退出了。

if ((flag2 && lpExitCode != 259) || (!flag2 && Marshal.GetLastWin32Error() == 6) || AppDomain.CurrentDomain.IsFinalizingForUnload())
	{
		if (!waitHandle.WaitOne(1, exitContext: false))
		{
			throw new InvalidAsynchronousStateException(SR.GetString("ThreadNoLongerValid"));
		}
		break;
	}
posted @ 2026-11-19 09:45  BruceNeter  阅读(277)  评论(0)    收藏  举报