开发者

Use backgroundworker in VC++ 2010

I want to mak开发者_运维技巧e a program that zip by backup files, but the program hangs when zipping files. I tried to use backgroundworker to execute the work.

this is my code so far:

private: System::Void threadTest_Click(System::Object^  sender, System::EventArgs^  e) {
         debug->Text = L"Zipping...";
         zip->RunWorkerAsync();
         if(zip->IsBusy)
         {
            bkProgress->Increment(20);
            Application::DoEvents();
         }
         //zip->OnDoWork();
     }

This is DoWork code for my backgroundworker:

private: System::Void zip_DoWork(System::Object^  sender, System::ComponentModel::DoWorkEventArgs^  e) {
            //zipping file code here
            refreshAll();
     }

I found out that refreshAll()won't run and I can't tell when the thread is stopped, I think I did something wrong here, can you give me some tips, I am really new to CLR. Thanks


if RefreshAll make changes to GUI, you have to take care to the following rule:

Never change the GUI from another thread than the main thread where the Gui was created.

In you case you have to use Form::Invoke method to switch to the main thread like that

this->Invoke(gcnew RefreshAllDelegate(), new Object[] { message });

And of course you have to create a delegate RefreshAllDelegate.


Delete all the code after RunWorkerAsync(), it will only make your app crash when the user closes the form while zipping is in progress. In the DoWork() method, use the bgw's ReportProgress() method to report progress. You can write an event handler for the event to update the UI. Move refreshAll() into the bgw's RunWorkerCompleted event handler.

Do review the examples giving the MSDN Library article for BackgroundWorker. BGW was designed to make multi-threading with the UI easy but if you are using it wrong then you'll just buy a lot of grief. Practice the examples first before making it work in your own code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜