Solve a cross-threading Exception in WinForms

后端 未结 6 1799
北荒
北荒 2020-12-01 17:14

Presently I\'m working with WinForms(in C#) and I have to run the application in the background. For this purpose I\'m using asynchronous. When I run the application it\'s s

6条回答
  •  一向
    一向 (楼主)
    2020-12-01 18:04

    A pattern you might find useful is to do a check at the top of functions that interact with the GUI to see whether you are running on the correct thread or not and have the function invoke itself if required. Like this:

        public delegate void InvocationDelegate();
    
        public void DoGuiStuff(){
          if (someControl.InvokeRequired){
            someControl.Invoke(InvocationDelegate(DoGuiStuff));
            return;  
          }
    
          //GUI manipulation here
        }
    

    Using this pattern - if you are on the correct thread when the method is called it doesn't invoke itself, but if you are on a different thread it will invoke itself and then return (so the GUI manipulation logic is only ever called once either way).

提交回复
热议问题