如何使MFC中的控件线程安全 [英] how to make controls thread safe in MFC
本文介绍了如何使MFC中的控件线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在项目中创建了一个线程,并且使用了丰富的编辑控件来显示数据.当我运行应用程序并尝试在Rich edit控件中显示数据时,它将挂起我的窗口.
所以我想使其成为线程安全的.解决方案是什么?
我已经使用以下代码创建了线程.
在h文件中
I have made one thread in my project and I use rich edit control to show data. When i run my appliaction and i try to show data in Rich edit control , It will hang my window.
So I want to make it thread-safe. What is the solution?
I have created thread using below code.
In h file
static unsigned long __stdcall ReadThread1(void *ptr)
{
((CSimpleTestDlg*)ptr)->ReadThread();
return 0;
}
在cpp文件中
In cpp file
void CSimpleTestDlg::OnBnClickedOk()
{
HANDLE rt;
DWORD dwReadThread;
rt = CreateThread(NULL , 0 , (LPTHREAD_START_ROUTINE)ReadThread1 , this , 0, &dwReadThread);
}
void CSimpleTestDlg::ReadThread()
{
//code
}
推荐答案
规则是:请勿在其他线程中使用UI函数或操作UI对象.
如果您希望线程更新UI对象,则可以发布或发送消息:该消息将由UI线程处理.
例如,假设您在CDialog
派生类中创建了一个线程:
在h文件中:
The rule is: never use UI functions or manipulate UI objects in another thread.
If you want a thread to update an UI object, you can for example post or send a message: the message will be handled by the UI thread.
For example, let''s say you created a thread inside aCDialog
-derived class:
In h file:
class CYourDialog : public CDialog
{
...
//the thread function
static DWORD WINAPI YourThread(LPVOID param);
...
//the message handler
afx_msg LRESULT OnYourMessage(WPARAM wParam, LPARAM lParam);
};
在cpp文件中:
In cpp file:
//define a user message. Replace x by 0, 1, 2, ..., to define different message IDs.
#define WM_YOUR_MESSAGE (WM_USER + x)
BEGIN_MESSAGE_MAP(CYourDialog, CDialog)
....
// map the message ID to the handler
ON_MESSAGE(WM_YOUR_MESSAGE, OnYourMessage)
END_MESSAGE_MAP()
DWORD WINAPI CYourDialog::YourThread(LPVOID param)
{
//when you create your thread
//give this pointer as a parameter so you can get the pointer back here
//get our dialog pointer
CYourDialog* pDlg = (CYourDialog*)param;
//SendMessage is synchronous: it will wait that the message is handled before returning
//be carefull with that function, because it can easily cause deadlocks
//if you block the main UI thread.
pDlg->SendMessage(WM_YOUR_MESSAGE, param1, param2);
//param1 and param2 can be pointers to structures: just cast them in LPARAM in WPARAM
...
return 0;
}
LRESULT CYourDialog::OnYourMessage(WPARAM wParam, LPARAM lParam)
{
//here you can cast wParam and lParam back to their real types
//your are in the UI thread, you can do whatever you want
return 0;
}
这篇关于如何使MFC中的控件线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文