【问题标题】:Why still Cross-thread operation not valid error with delegate Invoke?为什么委托调用仍然出现跨线程操作无效错误?
【发布时间】:2011-12-16 18:43:50
【问题描述】:

我有一个 VC++2008 表单应用程序,其中包含一些 非托管 套接字通信代码。我想在表单上显示通信消息。为了避免上述错误,我添加了 delegate 方法并使用了 Invoke 调用。但我仍然得到上述错误。有人可以帮我更正我的代码吗?

这是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:

static ProgressHandler^ updateHandler; static 不应该存在,它应该是private

错误发生在 updateLogMsg()

【问题讨论】:

    标签: .net visual-studio-2008 visual-c++


    【解决方案1】:

    委托的Invoke(args) 只是在当前线程上运行;你需要someControlInstance.Invoke(delegate, args)(很常见,“this.Invoke(...)”),它使用消息循环将委托调用转移到 UI 线程,避免了跨线程问题。

    同样;

    • Delegate.BeginInvoke 使用线程池
    • Control.BeginInvoke 使用消息循环

    【讨论】:

      猜你喜欢
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      相关资源
      最近更新 更多