首页 > 解决方案 > CPP - Async 不适用于 DLL 和 C-Sharp

问题描述

我想通过调用 DLL 中的方法从 Csharp 异步读取串行端口。请通过下面的简单代码。

夏普项目:

[DllImport("SerialTry.dll")]
public static extern void connectDevice();

static void Main(string[] args) {
  connectDevice();
  Console.WriteLine("Printed after reading 50 bytes connectDevice() - WHY?");
}

DLL 项目:

void connectDevice(){
    //Reads 50 Bytes and print byte number from serial port async
    auto result = std::async(std::launch::async, &DeviceControlActivity::read_data, this, std::ref(my_serial));
    cout << "Printing before reading 50 Bytes - EXPECTED!\n";
}
Output: 
Printing before reading 50 Bytes - EXPECTED!
#1 #2 #3 .... #50
Printed after reading 50 bytes connectDevice() - WHY?
Expected:
Printing before reading 50 Bytes - EXPECTED!
Printed after reading 50 bytes connectDevice() - WHY?
#1 #2 #3 .... #50

标签: c#c++asynchronousdll

解决方案


std::async返回一个std::future对象。从析构函数的文档中:

std::future::~future

这些操作不会阻塞共享状态准备就绪,除非满足以下所有条件时可能会阻塞:共享状态是通过调用 std::async 创建的,共享状态尚未准备好,并且这是对共享状态的最后引用

强调我的。据我所知,在您的示例中,所有这些条件都是正确的。

编辑:我对 std::async 一点也不熟悉,但从阅读文档来看,它似乎类似于Task.Run。如果是这样,对 c++ 代码进行同步调用并处理 c# 端的 async-stuff 应该相当简单。


推荐阅读