c# - WinForms - Enable button on AsyncCallback from a separate thread -


i new multi-threading and, so, sure it's quite possible entire question wrong, more me learn how things done right, hope you'll forgive , explanation set @ "idiot" level appreciated!!!!

suppose have following class external winform:

public class test {     public void runonseparatethread()     {         // function takes asynccallback parameter , runs asynchronously         // returns iasyncresult         foo(m_asynccallback);     }      private asynccallback m_asynccallback = new asynccallback(asynccomplete);     private static void asynccomplete(iasyncresult result)     {          // whatever disposal stuff needs done, etc.     } } 

now, have button on winform, that, when pressed:

  1. disables button
  2. runs runonseparatethread process on separate thread (not tie gui thread)

then, when async process complete:

  1. have asynccomplete method run in test class
  2. re-enable button on form (and maybe other things in form class)

as said, brand new me. i'm imagining done create asynccallback delegate on form , pass class (as property??) , have asynccomplete method run @ end, seems bad programming.

what best / correct way - please understand i'm major newbie on kind of stuff, i'd appreciate links / explanations understand correct way multi-thread scenario such this.

also, although written in c#, i'm equally comfortable in vb , c#, answer appreciated.

thanks!!!

i'll suggest use tpl instead of outdated apm approach unless requirements use old .net framework versions. question. ui frameworks don't allow ui modification non-main (non-ui) thread. so, should use invoke method post updates ui thread loop (or begininvoke execute delegate in async way). tpl pretty simple:

void button_click(object sender, eventargs e) {     button.enabled = false;     task.factory.startnew(() =>     {         //long-running stuff     }).continuewith((result) =>     {         button.enabled = true;     }, taskscheduler.fromcurrentsynchronizationcontext()); } 

please note, question asked broad, , it's better read articles on executing tasks in async way in winforms.

edit

if have no control on foo, code may this:

void button_click(object sender, eventargs e) {     button.enabled = false;     iasyncresult asyncresult = foo(...);     task.factory.fromasync(asyncresult, (result) =>     {         button.enabled = true;     }, taskcreationoptions.none, taskscheduler.fromcurrentsynchronizationcontext()); } 

Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -