Control.Invoke is hanging

扶醉桌前 提交于 2019-11-28 01:41:41

There's only one reason a Control.Invoke() call would hang. Or a BeginInvoke() call not executing its target, same thing. It happens when the main thread of the program, the UI thread, is not idle and busy doing something else.

What the "something else" could be is all over the map. The worst thing you could do have the main thread wait for the worker thread to complete. That's a guaranteed deadlock if you use Invoke().

The condition is very easy to diagnose, use Debug + Break All and Debug + Windows + Threads. Double-click the Main thread and look at the Call Stack window. The top of the stack trace should say "Managed to Native Transition", the one below it should be FPushMessageLoop(). If you see something else then you've found the code that causes the deadlock.

You are using Thread.Join to let the UI thread pause until the other thread is done. At the same time you use Control.Invoke to let the UI thread do some action. This won't work because the UI thread is waiting for the other thread to finish.

I would suggest you either remove the Thread.Join call or do your action in the UI thread if you want it to wait for the action to finish.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!