2013-05-03 21 views
3

enter image description here如何調用一個耗時的任務的DLL?

在我的WPF應用程序中,我必須通過串口與數據收發器進行通信。爲了簡單起見,我想將此通信分成一個類庫。

在我的DLL中,我將向數據收集器發出命令並等待10秒鐘以收到迴應。一旦我得到數據收集者的響應,我將數據編譯爲有意義的信息並傳遞給主應用程序。

我的問題是如何使主應用程序暫停一段時間從外部dll獲取數據,然後繼續處理來自dll的數據?

我使用.NET 4.0

+0

什麼版本的.NET?根據異步/等待,任務,BackgroundWorker線程,回調/事件。 – Belogix 2013-05-03 10:13:33

回答

3

考慮調用一個新的線程

Thread dllExecthread = new Thread(dllMethodToExecute); 

的DLL方法,並從主程序可以執行時完成的dll提供的回調(這可以防止鎖定在GUI上)。

編輯:或爲純樸的緣故,如果你只是想主程序等待DLL執行完隨後致電:

dllExecthread.Join(); 
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 
      }); 
1

唐永遠不會暫停你的主線程,因爲它阻塞了GUI。相反,您需要針對背景通信觸發的事件採取行動。您可以使用BackgroundWorker類 - 只需在RunWorkerCompleted中提供結果即可。

相關問題