外部中止线程
问:我有一个对话框,里面显示了一系列在一目录中可用的文件,我想当目录的 内容有所 变化时,对话框也能发生相应的变化,这需要从别的线程实现这个要 求,但怎样才能使该 线程能在对话框退出时同时关闭? 答:你可以做下面的一件事情就可以实现. -在对话框中调用TerminateThread(handle, exitcode). -使用信号量,当你 想关闭线程时只需检查该标志罢了. -在线程中使用消息循环,然后从对话框 调用PostThreadMessage 2)谢谢大家的回复,在大家的帮助下我的问题 已经解决了,现写出来给大家作参考. 问题是有一个对话框,里面显示了一 系列在一目录中可用的文件,我想当目录的内容有所 变化时,对话框也能发 生相应的变化.其实用一个新线程以及使用WaitForSingleObject() 循环就 可以了.但似乎不容易在退出对话框时中止线程,解决方法包括建立一个私 有事件 用WaitForMultipleObjects()等待.具体如下 BOOL CLocalNotes::OnInitDialog() { Cdialog::OnInitDialog(); Cstring eventname; // Generate a unique event name eventname.Format("Viewer %x", &eventname); m_FinishedHandle = CreateEvent(NULL, false, false, eventname); m_WatcherThread = AfxBeginThread(FileWatcher, this, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED, NULL); m_NotifyHandle=::FindFirstChangeNotification(m_PatDir, false, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME); m_WatcherThread->ResumeThread(); RefreshList(); // Generate the list of files return TRUE; } .... Static UINT FileWatcher(LPVOID TheNote) { CLocalNotes *OurNote = (CLocalNotes*)TheNote; HANDLE handle[2]; handle[0]=OurNote->NotifyHandle(); handle[1]=OurNote->FinishedHandle(); for (;;) { if (::WaitForMultipleObjects(2, handle, false, INFINITE) == WAIT_OBJECT_0+1) break; // Finished notification OurNote->RefreshList(); FindNextChangeNotification(OurNote->NotifyHandle()); } return 0; } .... CLocalNotes::~CLocalNotes() { ::SetEvent(m_FinishedHandle); WaitForSingleObject(m_WatcherThread->m_hThread, INFINITE); }