Automating the InvokeRequired code pattern

后端 未结 9 1307
醉话见心
醉话见心 2020-11-21 23:57

I have become painfully aware of just how often one needs to write the following code pattern in event-driven GUI code, where

private void DoGUISwitch() {
           


        
9条回答
  •  没有蜡笔的小新
    2020-11-22 00:35

    You should never be writing code that looks like this:

    private void DoGUISwitch() {
        if (object1.InvokeRequired) {
            object1.Invoke(new MethodInvoker(() => { DoGUISwitch(); }));
        } else {
            object1.Visible = true;
            object2.Visible = false;
        }
    }
    

    If you do have code that looks like this then your application is not thread-safe. It means that you have code which is already calling DoGUISwitch() from a different thread. It's too late to be checking to see if it's in a different thread. InvokeRequire must be called BEFORE you make a call to DoGUISwitch. You should not access any method or property from a different thread.

    Reference: Control.InvokeRequired Property where you can read the following:

    In addition to the InvokeRequired property, there are four methods on a control that are thread safe to call: Invoke, BeginInvoke, EndInvoke and CreateGraphics if the handle for the control has already been created.

    In a single CPU architecture there's no problem, but in a multi-CPU architecture you can cause part of the UI thread to be assigned to the processor where the calling code was running...and if that processor is different from where the UI thread was running then when the calling thread ends Windows will think that the UI thread has ended and will kill the application process i.e. your application will exit without error.

提交回复
热议问题