In general, when invoking UI controls in multithreading, it involves modifying the UI across threads, using delegates, such as the following:
this. Invoke ((methodinvoker)delegate { true; });
However, if I close the form prematurely when the multithreaded operation is not completed, InvalidOperationException will be thrown, prompting "invoke or BeginInvoke cannot be invoked on the control before the window handle is created"
, and if it is not captured, it can cause the program to crash and close directly.
After Baidu, found the need to determine the control ishandlecreated and Isdisposed properties, and if there are errors, you can catch the InvalidOperationException exception, to avoid the program crashes
But there are too many places in the project where you need to modify the UI, and it's too cumbersome to judge every time a UI change is involved.
At this point, it is best to write a class yourself, specifically responsible for processing multi-threaded UI calls, the code is as follows
Public Static classControlinvoker { Public Static voidInvoke (Control ctl, MethodInvoker method) {if(!ctl. ishandlecreated)return; if(ctl. isdisposed)return; if(ctl. invokerequired) {ctl. Invoke (method); } Else{method (); } } }
The code does not specifically capture InvalidOperationException, because the window handle does not create an issue after such a judgment in the code. If necessary, you can add in.
The call is written as follows:
Controlinvoker.invoke (Thisdelegate { true; });
Unlike the previous code, you can directly replace all code that calls the UI across threads. It solves the problem.
C # Multithreading When you modify a control, you are prompted not to invoke invoke or BeginInvoke on the control until the window handle is created