我从WPF应用程序中的c#代码访问C++ dll库。从ui线程访问dll时,我没有任何问题。但是我需要在C++ dll的代码运行时UI才能响应。所以我尝试从另一个线程访问它。但是,当我尝试在非UI线程中第一次调用相同的函数(我通过ui线程调用)时,该函数返回,但返回值指示函数中存在内部错误。但是当我从非UI线程运行代码时,它成功返回一个非错误值。我没有dll的源代码,所以我不知道里面会发生什么。在WPF中使用PInvoke与ui/non-ui线程差异
C++函数
UINT32 myfunc1()
在C#
[DllImport("mydll.dll")]
public static extern uint myfunc1();
我在UI线程如何到达代码
uint errorCode = myfunc1(); // returns 0 means no error occured
我在非UI线程如何到达代码
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s, args) => { args.Result = myfunc1(); };
// 1st call args.Result is 10 means internal error ocurred
// 2nd call args.Result is sometimes 0 and sometimes 10
// 3rd or later calls args.Result is 0 means no error occured
worker.RunWorkerCompleted += doSth();
worker.RunWorkerAsync();
什么是你的问题? –
我想问题是为什么第一次在非UI线程中调用dll函数时出现错误。 –