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:
- disables button
- runs
runonseparatethread
process on separate thread (not tie gui thread)
then, when async process complete:
- have
asynccomplete
method run intest
class - 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
Post a Comment