
在我的WPF应用程序中,我必须通过串行端口与数据存储进行通信。为简单起见,我想将此通信分离到一个类库中。
在我的DLL中,我将向数据存储发出一个命令,并等待10秒以接收返回的响应。一旦我从数据存储获得响应,我将数据编译成有意义的信息,并将其传递给主应用程序。
我的问题是如何使主应用程序暂停一段时间,以便从外部dll获取数据,然后继续处理来自dll的数据?
我使用.net 4.0
发布于 2013-05-03 18:15:57
考虑在新线程中调用DLL方法
Thread dllExecthread = new Thread(dllMethodToExecute);以及提供从主程序到dll的回调,该回调可以在完成时执行(这防止在GUI上锁定)。
edit:或者为了简单起见,如果您只想让主程序等待DLL完成执行,则随后调用:
dllExecthread.Join();发布于 2013-05-03 18:32:44
也许你可以使用TPL:
//this will call your method in background
var task = Task.Factory.StartNew(() => yourDll.YourMethodThatDoesCommunication());
//setup delegate to invoke when the background task completes
task.ContinueWith(t =>
{
//this will execute when the background task has completed
if (t.IsFaulted)
{
//somehow handle exception in t.Exception
return;
}
var result = t.Result;
//process result
});发布于 2013-05-03 19:07:08
永远不要暂停你的主线程,因为它会阻塞GUI。相反,您需要对后台通信触发的事件执行操作。您可以使用BackgroundWorker类-只需在RunWorkerCompleted中提供结果。
https://stackoverflow.com/questions/16356457
复制相似问题