C#Win Api DDE连接多线程

Maj*_*jak 7 c# multithreading dde

我在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
        );
Run Code Online (Sandbox Code Playgroud)

如果我打电话DdeInitializeW,并DdeConnect在不同的线程,DdeConnect返回空指针.

此外,如果我在一个线程中调用它们(已建立的DDE连接),我不能在另一个线程中使用此DDE通道(我收到INVALIDPARAMETERDDE错误).

正如我所说,一切都在单线程中没有问题.

Ben*_*Ben 7

您描述的行为是预期的.

DDE与单个线程相关联.这是因为DDE(通常被认为是传统技术)通过传递窗口消息在内部工作,而窗口句柄(HWND)具有线程关联性.

  • 您必须DdeInitializeW从您调用的同一个线程中调用DdeConnect.
  • 该线程必须泵送消息(因此它不能是线程池线程).
  • 您也将在同一个线程上获得回调/回复.

换句话说,您需要从调用的线程执行DDE Application.Run,或者Application.DoEvents在适合发送或接收事件的时刻经常调用.

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