[英]Access to main dialog variables within thread (MFC)
I have a GUI application with MFC. 我有MFC的GUI应用程序。 I'am lauching thread to process some data using AfxBeginThread().
我正在启动线程以使用AfxBeginThread()处理一些数据。 And i've got problem accessing to main dialog in thread:
而且我在线程中访问主对话框时遇到问题:
Through this struct I'am passing main dialog handler and pointer to main dlg object to thread. 通过此结构,我将主对话处理程序和指向主dlg对象的指针传递给线程。 But at strcpy() line debugger stops and shows pDlg->0x430f0020 {CTabDlg hWnd=???}
但是在strcpy()行调试器停止并显示pDlg-> 0x430f0020 {CTabDlg hWnd = ???}
typedef struct {
LPVOID myHandle;
LPVOID myPointer;
} sParamData;
UINT WorkerThreadProc_type2( LPVOID Param )
{
UpdInfo info;
sParamData *s;
s = (sParamData*)Param;
HWND hMainHandle = (HWND) (*s).myHandle;
CtabDlg* pDlg = (CtabDlg*)(*s).myPointer;
strcpy(apikey, pDlg->m_sVar);
...
}
I tried both XP and Windows 7 OS. 我尝试了XP和Windows 7 OS。 In XP it always crashes, but in Seven it works.
在XP中它总是崩溃,但在七个中它可以工作。 This is how i pass the struct to the thread:
这就是我将结构传递给线程的方式:
sParamData s;
s.myHandle = (HWND)GetSafeHwnd();
s.myPointer = (CtabDlg*) this;
if(CurrTab == 1)
{
AfxBeginThread(WorkerThreadProc_type2, &s, THREAD_PRIORITY_NORMAL,0,0,NULL);
pPage2->GetDlgItem(IDC_BUTTON1)->EnableWindow(FALSE);
Thank you for your time! 感谢您的时间!
If your code is exactly as your real case then here you are declaring a local sParamData and passing its address to thread. 如果您的代码与实际情况完全一样,那么您在这里声明一个本地sParamData并将其地址传递给线程。 This gives a race condition: s can go out of scope before the thread start execution, (or reaches the point where its content is copied).
这提供了一个竞争条件:s可以在线程开始执行之前超出范围(或到达复制其内容的位置)。
sParamData s;
s.myHandle = (HWND)GetSafeHwnd();
s.myPointer = (CtabDlg*) this;
if(CurrTab == 1)
{
AfxBeginThread(WorkerThreadProc_type2, &s, THREAD_PRIORITY_NORMAL,0,0,NULL);
pPage2->GetDlgItem(IDC_BUTTON1)->EnableWindow(FALSE);
The simplest workaround is probably allocate s on heap and delete it in thread after its content has been copied. 最简单的解决方法可能是在堆上分配s,并在其内容被复制后在线程中将其删除。
Like this: 像这样:
sParamData *s = new sParamData ;
s->myHandle = (HWND)GetSafeHwnd();
s->myPointer = (CtabDlg*) this;
if(CurrTab == 1)
{
AfxBeginThread(WorkerThreadProc_type2, s, THREAD_PRIORITY_NORMAL,0,0,NULL);
pPage2->GetDlgItem(IDC_BUTTON1)->EnableWindow(FALSE);
And then, inside the thread 然后,在线程内
UINT WorkerThreadProc_type2( LPVOID Param )
{
UpdInfo info;
sParamData *s = (sParamData*)Param;
HWND hMainHandle = (HWND) s->myHandle;
CtabDlg* pDlg = (CtabDlg*)s->.myPointer;
// assuming s will no longer be used you can delete it here
delete s ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.