What's wrong with my cross-thread call in Windows Forms?

后端 未结 7 1897
南笙
南笙 2021-01-04 22:32

I encounter a problem with a Windows Forms application.

A form must be displayed from another thread. So in the form class, I have the following code:



        
7条回答
  •  北海茫月
    2021-01-04 23:18

    I believe what is happening here is that this code is being run before the Form is ever shown.

    When a Form is created in .Net it does not immediately gain affinity for a particular thread. Only when certain operations are performed like showing it or grabbing the handle does it gain affinity. Before that happens it's hard for InvokeRequired to function correctly.

    In this particular case no affinity is established and no parent control exists so InvokeRequired returns false since it can't determine the original thread.

    The way to fix this is to establish affinity for your control when it's created on the UI thread. The best way to do this is just to ask the control for it's handle property.

    var notUsed = control.Handle;
    

提交回复
热议问题