【问题标题】:CPP - Async not working with DLL and C-SharpCPP - Async 不适用于 DLL 和 C-Sharp
【发布时间】:2021-08-24 12:58:55
【问题描述】:

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

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++ asynchronous dll


    【解决方案1】:

    std::async 返回一个std::future 对象。来自析构函数的documentation

    std::future::~future

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

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

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

    【讨论】:

    • 如果不是异步/未来,您是否建议任何其他方法?
    • @suraj Jorwekar 添加了关于 task.run 的部分。
    • 将异步添加到 C# 是一种方法,但出于某种原因,我不想在 C# 端添加任何异步/任务/线程登录并纯粹在 CPP 中处理。
    • 另外,我尝试使用 std::thread 并且结果是相同的,而分离 [thread1.detach()] 线程给出了预期的输出但突然结束,没有我假设 DLLMain 的串行读取负责作为线程析构函数。
    猜你喜欢
    • 1970-01-01
    • 2012-03-09
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 2021-09-11
    • 2015-02-04
    相关资源
    最近更新 更多