I have been writing a c++ code for myself,which iterates in a directory and will move files in to a directory of the same name as the file
\\\\
void foldersFrame::OnButton2Click(wxCommandEvent& event)
{
wxFileName mkr;
StaticText1->SetLabel(_("0"));
wxString fn;
wxString newf;
wxDir *dir=new wxDir(TextCtrl1->GetLabel());
bool cont = dir->GetFirst(&fn);
while (cont)
{
int mm=fn.Find('.',true);
newf=fn.Mid(0,mm);
if(! mkr.DirExists(dir->GetName()+_("\\")+fn)){
StaticText2->SetLabel(_("copying ")+fn);
if (! mkr.DirExists(dir->GetName()+_("\\")+newf)){
mkr.Mkdir(dir->GetName()+_("\\")+newf);
if (wxCopyFile(dir->GetName()+_("\\")+fn,dir->GetName()+_("\\")+newf+_("\\")+fn)){
wxRemoveFile(dir->GetName()+_("\\")+fn);
}
newf=StaticText1->GetLabel();
long d1;
if(!newf.ToLong(&d1));
d1+=1;
StaticText1->SetLabel(wxString::Format(wxT("%i"),d1));
}
}
cont = dir->GetNext(&fn);
}
wxSafeShowMessage(_("Message"),_("Finished"));
}
But the code i have written seem to be very inefficient.It takes a lot of time to move files,and the window doesn’t respond while copying.Someone please help me rewrite it..!!!!
You have two standard ways to implement a long running task.
First one, and by far the best, is to perform this task in a separate background thread. You can update the state of the GUI controls in the main thread by posting
wxThreadEventcontaining the progress data to the main window easily. The only complication — but a pretty important one — in this case is to handle closing the window/application termination/thread exit correctly.Second one, which could do in a pinch, is to do the task in
wxEVT_IDLEhandler piece by piece and callwxIdleEvent::RequestMore()after each step. This is not as responsive as using a separate thread because you still block the event handling during the handler execution and the code needs to be rewritten in a different way to be able to resume from where it left off.Using
wxYield()is a pretty bad idea and should be avoided unless no other solution can be implemented.