2012-03-30 26 views
0

我閱讀了一些關於如何將數據從Workerthread傳遞到主窗口(對話框)的主題,但我仍然不明白,仍然需要幫助。 我的workerthread應該處理一些計算,並在每個循環中將結果顯示在GUI上進行編輯。我知道,我應該使用PostMessage的,但因爲我正在做的計算意味着控制元件,我不知道如何解決這個問題?MFC - 通過PostMessage發佈數據到GUI

//CWorkerThreadMgr.h manages the second thread 
HRESULT Start (HWND hWnd);// from where the workerthread will be started 

HWND m_hWnd ; //Window handle to the UI ; 

HANDLE m_hTread; //handle of the worker thread 

static UINT WINAPI ThreadProc(LPVOID lptest); 

static UINT WINAPI ThreadProc(LPVOID lptest) 

{  
    CWorkerThreadMgr* pCalculateMgr = reinterpret_cast< CWorkerThreadMgr*(lptest); 

//The following operation:rand() *m_Slider.GetPos() should 

//should be calculated and the result displayed each time in the edit box in the gui 

for(UINT uCount = 0; uCount < 40; uCount++){ 

pCalculateMgr->rand() *m_Slider.GetPos();//?don't allowed to touch the gui!! 

PostMessage(pCalculateMgr-> m_hWnd, WM_SENDCALCULATED_VALUE,wparam(rand() *m_Slider.GetPos(),0); 
} 
} 

LRESULT CStartCalculationDlg::OnSendCalculatedValue(WPARAM Result, LPARAM) 

{ 
    // The resut should be displayed in the edit box 

     m_Calculation.Format(_T("%d"),???); 
     SetDlgItemText(IDC_CALCULATION, m_Calculation); 

    return 1; 
} 

void CStartCalculationDlg::OnHScroll(UINT nSBCode, UINT nPos,CScrollBar* pScrollBar) 
{ 
    m_SliderValue.Format(_T("%d"),m_Slider.GetPos()); 
    SetDlgItemText(IDC_SLIDER_VALUE,m_SliderValue); 
} 

// Implementation in the CStartCalculationDlg.h 

CWorkerThreadMgr m_WorkerThreadMgr //instance of the WorkerThreadMgr 
CSliderCtrl m_Slider //member variable of the slider control 
CString m_SliderValue // member variable of the edit box, where the current value of the 
         //slider will be displayed 
CString m_Calculation // member variable of the edit box where the calculated 
         //result from the workerthread will be displayed via PostMessage 
afx_msg LRESULT OnSendCalculatedValue(WPARAM, LPARAM); 
afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); 

下probem的是,當我的滑塊控件被移動並獲得一個新的值,線程過程應該知道它並更新滑塊的值。我怎樣才能做到這一點?

+0

你可以將滑塊位置作爲參數傳遞給線程嗎? – Jeeva 2012-04-02 03:32:36

回答

0

而不是從工作線程讀取滑塊位置,請在UI線程中讀取它,並使其可用於工作線程。

我真的沒有這方面的專家,但我已經做了一些工作線程,如解釋here

在你的情況下,我會做的是創建一個靜態變量,如上面鏈接的文章中使用的「running」標誌,以保存滑塊的當前位置。然後,在OnHScroll處理程序中將其設置爲適當的值。

只要你只從一個線程寫入該變量,就不應該有同步問題。

0

從工作線程:

m_data = foo(); 
PostMessage(hWndMain, UWM_SOME_CUSTOM_MESSAGE, 0, 0); 

從UI線程:

LRESULT CMainFrame::OnSomeCustomMessage(WPARAM wParam, LPARAM lParam) 
{ 
    CMyData data = m_pWorker->GetData(); 
    // Do stuff... 
    return 0; 
} 

GetData必須由一個關鍵部分加以防護:

CMyData CMyWorker::GetData() 
{ 
    // This critical section is used in the worker thread too, whenever m_data is accessed. 
    m_lock.Lock(); 
    CMyData data = m_data; 
    m_lock.Unlock(); 

    return data; 
} 

CCriticalSection MSDN上。