.net - Waiting DownloadFileAsync with ManualResetEvent c++/cli -
i'm having little frustrating problem in c++/cli windows forms application.
so problem have download file webserver using webclient istance. use downloadfile , not downoadfileasyn, if want show progress bar showing progress of download file, must use downloadfileasyn. how can wait process of downloading until it's finished ?
the code is:
ref class example{ private: static system::threading::manualresetevent^ mre = gcnew system::threading::manualresetevent(false); public: void download(); void downloadfilecompleted(object^ sender, system::componentmodel::asynccompletedeventargs^ e); }; void example::download(){ webclient^ request = gcnew webclient; request->credentials = gcnew networkcredential("anonymous", "anonymous"); request->downloadfilecompleted += gcnew system::componentmodel::asynccompletedeventhandler(this,&filecrypt::downloadfilecompleted); request->downloadfileasync(gcnew uri("ftp://ftp...."+remote_path),remote_file,mre); mre->waitone(); /* block of instructions want run after file download completed */ } void example::downloadfilecompleted(object^ sender, system::componentmodel::asynccompletedeventargs^ e){ messagebox::show("completed"); mre->set(); }
so when download completed, program stop running , doesn't run block of instructions above written, after mre->waitone() instruction. downloadfilecompleted() not executed, in fact messagebox shown.
any ideas? i've serarched problem, , many people had it, in c# only. , i've "translated" solution c# c++. doesn't work...
you cannot wait, causes deadlock. downloadfilecompleted() method cannot run until main thread goes idle , re-enters dispatcher loop. isn't idle, stuck in waitone() call. method cannot run , mre can't set. in turn causes waitone() never complete. deadly embrace program can never recover. 1 of standard threading bugs.
it isn't clear why wait, there no point waitone() call @ posted. can delete , works fine. maybe there's code after in real program, must move code downloadfilecompleted() method.
the general programming rule threads display ui applies here. can never sleep , can never block. doing makes ui unresponsive , raises odds deadlock. ui event-driven, events triggered example user moving mouse or pressing key. code runs when event fired can run when thread isn't doing else. download completion signaled event.
Comments
Post a Comment