gpt4 book ai didi

c# - 在 C# 程序中避免这种竞争条件

转载 作者:行者123 更新时间:2023-11-28 03:40:36 25 4
gpt4 key购买 nike

我正在开发 C# 应用程序,遇到一个奇怪的问题。我有一个用 C++ 构建的 .dll,我必须从 C# 应用程序调用这个 .dll 中的一些函数。

考虑这个示例代码:

public partial class MainWindows: Window
{
public MainWindow()
{
InitializeComponent();
ConfigurationFunctions.StartMain(); //Start main is the DLL function in C++

int x = ConfigurationFunctions.ReturnIntExp();
StringBuilder sb = ConfigurationOptions.ReturnSomethingExp();
}
}

C++ .cpp 文件

EXPORT_API int xExp;
EXPORT_API char cExp;
EXPORT_API StartMain()
{
//Calculate `x` and `y` in this program values here and allocate to variables to be returned from function
xExp = x;
cExp = c;
}
EXPORT_API int ReturnIntExp()
{
return xExp;
}
EXPORT_API char ReturnSomethingExp()
{
return cExp;
}

问题是当我从 .dll 运行 StartMain() 函数时,它会为 intchar 计算一些值,这必须分配给变量(实际上返回给 C# 应用程序)

但是,在 StartMain() 之后,C# 应用程序应该等到 StartMain() 函数完成(在这种情况下大约需要 3-4 秒,并且dll 本身会触发两个/三个其他进程)然后才继续进行,否则,C# 应用程序中的变量 xsb 将具有空值/无意义的值。

在这种情况下我怎样才能达到同样的效果?

最佳答案

添加第三个导出变量 ReturnIsReady(),如果其他两个方法具有有意义的数据,则返回 true,否则返回 false。然后简单地使用一个带有 sleep 的循环来检查该值,直到它发生变化。

更好的选择是实现互斥锁或类似结构,但自旋等待对于启动时的单个等待时间应该足够了。

或者,为什么 StartMain() 在填写值之前返回?

关于c# - 在 C# 程序中避免这种竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9398501/

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