在 C# 程序中避免这种竞争条件
我正在开发一个 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()
函数时,它会计算 int< 的一些值/code> 和
char
必须分配给变量(实际上返回到 C# 应用程序)
但是,在 StartMain()
之后,C# 应用程序应该等到 StartMain()
函数完成(在本例中大约需要 3-4 秒,并且 dll 本身会触发两个/三个其他进程),然后才继续进一步操作,否则变量 x
和 sb
在 C# 应用程序中将有空/无意义的值。
在这种情况下我怎样才能达到同样的效果?
I am working on a C# application and facing a strange issue here. I have a .dll which has been built in C++, and I have to call some functions from this .dll from C# app.
Consider this sample code:
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 file
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;
}
The problem is when I run the StartMain()
function from the .dll, it calculate some values for for int
and char
which have to be allocated to variables (that are actually returned to C# application)
But, after StartMain()
the C# application should wait till the StartMain()
function is complete (which in this case takes approx. 3-4 secs and the dll itself fires two/three other processes) and only then proceed further or else, the variables x
and sb
in C# application will have empty/meaningless values.
How can I achieve the same in this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
添加第三个导出变量
ReturnIsReady()
,如果其他两个方法有有意义的数据,则返回true
,否则返回false
。然后简单地有一个带有睡眠的循环来检查该值,直到它发生变化。更好的选择是实现互斥体或类似的结构,但自旋等待对于启动时该长度的单次等待来说应该足够了。
或者,为什么
StartMain()
在填写值之前返回?Add a third exported variable
ReturnIsReady()
that returnstrue
if the other two methods have meaningful data, andfalse
otherwise. Then simply have a loop with a sleep to check that value until it changes.A better option would be to implement a mutex or similar structure, but spin waiting should be sufficient for a single wait of that length at start up.
Alternatively, why is
StartMain()
returning before filling in the values?