gpt4 book ai didi

C# Win Api DDE连接多线程

转载 作者:太空狗 更新时间:2023-10-29 20:20:04 29 4
gpt4 key购买 nike

我在 C# 中使用 Win Api 实现了 DDE 客户端的功能。如果我在单线程中调用 DdeInitializeWDdeConnect,一切正常。具体来说,这些是包装器定义:

    [DllImport("user32.dll")]
protected static extern int DdeInitializeW(ref int id, DDECallback cb, int afcmd, int ulres);

[DllImport("user32.dll")]
static extern IntPtr DdeConnect(
int idInst, // instance identifier
IntPtr hszService, // handle to service name string
IntPtr hszTopic, // handle to topic name string
IntPtr pCC // context data
);

如果我在不同线程中调用 DdeInitializeWDdeConnectDdeConnect 返回空指针。

此外,如果我在一个线程中同时调用了它们(已建立的 DDE 连接),我将无法在另一个线程中使用此 DDE channel (我收到 INVALIDPRAMETER DDE 错误)。

正如我所说,在单线程中一切正常。

最佳答案

您描述的行为是预期的。

DDE 绑定(bind)到单个线程。这是因为 DDE(通常被认为是遗留技术)通过传递窗口消息在内部工作,并且窗口句柄 (HWND) 具有线程关联性。

  • 您必须从调用 DdeConnect 的同一个线程调用 DdeInitializeW
  • 该线程必须发送消息(因此它不能是线程池线程)。
  • 您也会在同一个线程上收到回调/回复。

换句话说,您需要从调用 Application.Run 的线程执行 DDE,或者在适当的时候频繁调用 Application.DoEvents要发送或接收的事件。

您可以在多个线程中使用 DDE,但每个线程都必须调用 DdeInitializeW,并且始终会在发送请求的线程上接收回复。

关于C# Win Api DDE连接多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32734552/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com