我用C++编写了一些后端代码,并用C#为它编写了一个前端.我想让它做的是在后台运行后端代码,这样我就可以做其他事情,比如更新进度条,但当我单击"开始"按钮时,程序会挂起,直到它运行完后端代码.
C#代码:
[DllImport("backend.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int executeBackend();
private async void startButton_Click(object sender, EventArgs e)
{
startButton.Enabled = false;
await StartProgram();
}
private async Task StartProgram()
{
int status = 0;
status = executeBackend(); //This is causing the UI to deadlock
startButton.Enabled = true;
}
Ackend.dll C++代码:
extern "C" {
__declspec(dllexport) int executeBackend()
{
int statusCode = 0;
//Do stuff in the background
return statusCode;
}
}
如果我注释掉运行ecuteBackend的调用并将其替换为await Task.Delay(5000);
,则UI不会死锁.我该怎么解决这件事?