.net 为什么委托调用仍然存在跨线程操作无效错误?
我有一个VC++2008表单应用程序,其中包含一些非托管的套接字通信代码。我想在表单上显示通信消息。为了避免上述错误,我添加了delegate方法并使用了Invoke调用。但我还是犯了以上的错误。有人能帮我更正代码吗 这是表单1头文件:.net 为什么委托调用仍然存在跨线程操作无效错误?,.net,visual-studio-2008,visual-c++,.net,Visual Studio 2008,Visual C++,我有一个VC++2008表单应用程序,其中包含一些非托管的套接字通信代码。我想在表单上显示通信消息。为了避免上述错误,我添加了delegate方法并使用了Invoke调用。但我还是犯了以上的错误。有人能帮我更正代码吗 这是表单1头文件: #pragma once #include "SocketClientMgr.h" class SocketClientMgr; namespace SocketClientFormApp { public ref class Form1 : pu
#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);
};
}
#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);
}
这是Form1 cpp文件:
#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);
};
}
#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()上发生错误。
委托的调用(args)
仅在当前线程上运行;您需要someControlInstance.Invoke(delegate,args)
(通常是“this.Invoke(…)”),它使用消息循环将委托调用传输到UI线程,从而避免跨线程问题
平等地
- Delegate.BeginInvoke使用线程池
- Control.BeginInvoke使用te消息循环