c# - Creating a MethodInvoker function -


so have multi threaded application. ran error "cross-thread operation not valid: control accessed thread other thread created on."

my thread calling windows forms control. around used

control.invoke(new methodinvoker(delegate { controlsaction; }));

i trying figure out way make generic method can reuse code , make app alot cleaner.

so instance, on of invokes following rich text box.

rtboutput.invoke(new methodinvoker(delegate {     rtboutput.appendtext(fields[0].trimstart().trimend().tostring() + " profile not    removed.  check logs.\n"); })); 

another combo box setting text.

cmbemailprofile.invoke(new methodinvoker(delegate { emailprofilenametosetforusers =  cmbemailprofile.text; })); 

another example again rich text box clearing it.

 rtboutput.invoke(new methodinvoker(delegate { rtboutput.clear(); })); 

how create generic function me need pass in control action want do?

this have come far.

private void methodinvoker(control sender, action act)     {         sender.invoke(new methodinvoker(act));     } 

so problem appendtext, doesn't seem like.

something should trick:

public static class formsext {     public static void invokeonmainthread(this system.windows.forms.control control, action act)     {         control.invoke(new methodinvoker(act), null);     } } 

and using simple as:

        var lbl = new system.windows.forms.label();         lbl.invokeonmainthread(() =>             {                // code run on main thread here             }); 

with original label:

        rtboutput.invokeonmainthread(() =>             {                // code run on main thread here                rtboutput.appendtext(fields[0].trimstart().trimend().tostring() + " profile not removed.  check logs.\n"); }));             }); 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -