mfc中的异步方法调用
问题描述:
我想调用一个函数Recurse(LPCTSTR pstr)来扫描文件,同时又想做另一个任务但是当我点击Resume Button时我必须等到整个扫描结束。
我该怎么办...
我尝试了什么:
I wanted to call a function Recurse(LPCTSTR pstr) to scan files and at the same time wanted to do another task but when I'm clicking on Resume Button I have to wait Until whole scanning finished.
what should I do...
What I have tried:
void CPracticePictureControlandlabelsDlg::OnBnClickedResume()
{
// TODO: Add your control notification handler code here
Recurse(L"E:\\");
}
void CPracticePictureControlandlabelsDlg::Recurse(LPCTSTR pstr)
{
m_picProgressGif.Draw();
m_picMyimg.Draw();
CFileFind finder;
// build a string with wildcards
CString strWildcard(pstr);
strWildcard += _T("\\*.*");
// start working for files
BOOL bWorking = finder.FindFile(strWildcard);
while (bWorking)
{
bWorking = finder.FindNextFile();
// skip . and .. files; otherwise, we'd
// recur infinitely!
if (finder.IsDots())
continue;
// if it's a directory, recursively search it
if (finder.IsDirectory())
{
CString str = finder.GetFilePath();
m_lblMessage.SetText(str);
Recurse(str);
}
}
finder.Close();
}
答
您必须创建一个在后台执行操作的工作线程。
但MFC不是线程安全的,因此如果要从线程更新GUI元素,则必须实现某种信令,如发送用户定义的Windows消息。
您可能还需要跟踪线程的状态(运行或退出)以避免再次启动它/另一个线程并在工作线程发出时发出主线程信号工作完成后终止。如果工作线程可能运行较长时间,则可能还需要实现一个kill机制(按下Stop按钮或终止应用程序时)。
一些读物:
使用C ++和MFC进行多线程处理 [ ^ ]
使用工作线程 [ ^ ]
简单线程:第一部分 [ ^ ]
You have to create a worker thread that performs the operation in the background.
But MFC is not thread safe so that you have to implement some kind of signaling like sending user defined Windows messages if you want to update GUI elements from the thread.
You might also need to track the state of the thread (running or exited) to avoid starting it again / another one and signal your main thread when the worker thread is terminating after the work is done. If the worker thread might run for a longer time it might be also necessary to implement a kill mechanism (called upon a Stop button press or when the application is terminated).
Some readings:
Multithreading with C++ and MFC[^]
Using Worker Threads[^]
Simple Thread: Part I[^]