For WinForm Software, do not operate the UI in the thread, do not believe: Startform.checkforillegalcrossthreadcalls = false;
So, all the code is changed to the main thread delegate invocation way
Private delegate void Settexthandle (string id, string value); private void Threadsettext (string id, String value) {this . Controls.find (ID, true) [0]. Text = value; } private void SetText (string id, String value) { if (this. InvokeRequired) {this . Invoke (New Settexthandle (Threadsettext), new object[] {ID, value}); } else { threadsettext (ID, value); } }
2
The canonical form (C # Consumer) public delegate void Controlstringconsumer (Control control, string text); Defines a delegate typepublic void SetText (Control control, string text) { if (control. invokerequired) { control. Invoke (New Controlstringconsumer (SetText), new Object[]{control, text}); Invoking itself } else { control. Text=text; The "Functional part", executing only on the main thread }}
3
public static class controlhelpers{public static void invokeifrequired<t> (this T control, action<t> Action) where T:isynchronizeinvoke { if (control. invokerequired) { control. Invoke (New action (() = = Action (control)), null); } else { action (control);}} }
Use it like this:
private updatesummary (string Text) { Summaryinvokeifrequired (s => { S. Text = text }); /span>
3
Thelabel.invoke (New Action (() = Thelabel.text = "Hello World from Worker thread!"));
4
public static void invokeifrequired (this control control, MethodInvoker action) { if (control. invokerequired) { control. Invoke (action); } else { action ();} }
Call:
Richeditcontrol1.invokeifrequired (() =>{ //Do anything you want with the control here Richeditcontrol1.rtftext = value; Rtfhelpers.addmissingstyles (richEditControl1);});
Updated to:
public static void invokeifrequired (this isynchronizeinvoke obj, methodinvoker action) { if (obj. invokerequired) { var args = new Object[0]; Obj. Invoke (action, args); } else { action ();} }
Consider when an exception still occurs:
while (!control.Visible){ System.Threading.Thread.Sleep(50);}
5
public static void invokeifrequired (this Control C, action<control> Action) { if (c.invokerequired) { C.invoke (New action (() = action (c))); else { action (c); }}
Change to:
public static void Invokeifrequired<t> (this T C, action<t> Action) where T:control
Call Method:
Object1. Invokeifrequired (c + = {c.visible = true;});
WinForm software, do not operate the UI in the thread