如何调用执行耗时任务的DLL?

时间:2013-05-03 10:09:56

标签: c#

enter image description here

在我的WPF应用程序中,我必须通过串行端口与数据存储器进行通信。为简单起见,我想将此通信分成类库。

在我的DLL中,我将向数据存储器发出命令并等待10秒钟以接收响应。一旦我从数据存储器获得响应,我将数据编译为有意义的信息并传递给主应用程序。

我的问题是如何使主应用程序暂停一段时间以从外部dll获取数据,然后继续处理来自dll的数据?

我使用.net 4.0

3 个答案:

答案 0 :(得分:3)

考虑在新线程中调用DLL方法

Thread dllExecthread = new Thread(dllMethodToExecute);

并提供从主程序到dll的回调,这可以在完成时执行(这可以防止在GUI上锁定)。

编辑:或者为了简单起见,如果你只是想让主程序等待DLL完成执行,随后调用:

dllExecthread.Join();

答案 1 :(得分:1)

也许你可以选择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
            });

答案 2 :(得分:1)

不要暂停主线程,因为它会阻止GUI。相反,您需要对后台通信触发的事件采取行动。您可以使用BackgroundWorker类 - 只需在RunWorkerCompleted中提供结果。

相关问题