2011-12-16 88 views
1

我有一個VC++ 2008窗體應用程序與一些非託管套接字通信代碼。我想在表單上顯示通訊信息。爲了避免上述錯誤,我添加了代表方法並用調用調用。但我仍然遇到以上錯誤。任何人都可以幫我糾正我的代碼?爲什麼仍然使用委託調用跨線程操作無效錯誤?

這是Form1的頭文件

#pragma once 

#include "SocketClientMgr.h" 
class SocketClientMgr; 

namespace SocketClientFormApp { 

    public ref class Form1 : public System::Windows::Forms::Form 
    { 
    public: 
     Form1(void) 
     { 
      InitializeComponent(); 
      updateHandler = gcnew ProgressHandler(this, &SocketClientFormApp::Form1::updateLogMsg); 
     } 
    protected: 
     ~Form1() 
     { 
     } 
    private: 

#pragma region Windows Form Designer generated code 

     void InitializeComponent(void) 
     { 
     } 
#pragma endregion 

/////////////////////////////////// 

    private: delegate void ProgressHandler(String^ msg); 
    static ProgressHandler^ updateHandler; 

    public: void appendMsg(String^ msg); 
    public: void updateLogMsg(String^ msg); 
}; 
} 

這是Form1中CPP文件

#include "stdafx.h" 
#include "SocketClientForm.h" 

using namespace SocketClientFormApp; 

void Form1::appendMsg(String^ msg) 
{ 
    updateHandler->Invoke(msg); 
} 

void Form1::updateLogMsg(String^ msg) 
{ 
    msgDisplayBox->AppendText(msg); 
} 

appendMsg()方法將從另一類稱爲另一個線程

EIDT:

靜態ProgressHandler^updateHandler;靜態不應該在那裏,它應該是發生在updateLogMsg()私人

錯誤 enter image description here

回答

2

委託的Invoke(args)只是運行在當前線程;你需要someControlInstance.Invoke(delegate, args)(相當普遍的是「this.Invoke(...)」),它使用消息循環將委託調用轉移到UI線程,避免了跨線程問題。

同樣;

  • Delegate.BeginInvoke使用線程池
  • Control.BeginInvoke使用TE消息迴路