2016-07-29 54 views
5

我正在構建一個Windows服務,該服務使用named pipe與其他進程進行通信。 我對命名管道的通信單元測試引發此錯誤消息4次:如何確保在完成之前停止測試所啓動的所有線程

System.AppDomainUnloadedException:試圖訪問一個卸載 應用程序域。如果測試開始一個線程但沒有 就停止它,這可能會發生。確保測試開始的所有線程均爲 在完成之前停止。

這裏是我的單元測試:

[TestMethod] 
    public void ListenToNamedPipeTest() 
    { 
     var watcher = new ManualResetEvent(false); 

     var svc = new WindowService(); 
     svc.ClientMessageHandler += (connection, message) => watcher.Reset(); 
     svc.ListenToNamedPipe(); 
     sendMessageToNamedPipe("bla"); 
     var wait = watcher.WaitOne(1000); 

     svc.Dispose(); 

     Assert.IsTrue(wait, "No messages received after 1 seconds"); 
    } 

    private void sendMessageToNamedPipe(string text) 
    { 
     var client = new NamedPipeClient<Message, Message>(DeviceCertificateService.PIPE_NAME); 
     client.ServerMessage += (conn, message) => Console.WriteLine("Server says: {0}", message.Text); 

     // Start up the client asynchronously and connect to the specified server pipe. 
     // This method will return immediately while the client runs in a separate background thread. 
     client.Start(); 

     client.PushMessage(new Message { Text = text }); 

     client.Stop(); 
    } 

如何使所有的線程停止我的單元測試停止之前?

感謝


UPDATE:

命名管道客戶端沒有一個close()功能:

// Type: NamedPipeWrapper.NamedPipeClient`2 
// Assembly: NamedPipeWrapper, Version=1.5.0.0, Culture=neutral, PublicKeyToken=null 
// MVID: D2B99F4D-8C17-4DB6-8A02-29DCF82A4118 
// Assembly location: C:\Users\Thang.Duong\Source\Workspaces\Post Tracking System\Applications\Dev\OHD\packages\NamedPipeWrapper.1.5.0\lib\net40\NamedPipeWrapper.dll 

using System; 

namespace NamedPipeWrapper 
{ 
    public class NamedPipeClient<TRead, TWrite> where TRead : class where TWrite : class 
    { 
    public NamedPipeClient(string pipeName); 
    public void Start(); 
    public void PushMessage(TWrite message); 
    public void Stop(); 
    public void WaitForConnection(); 
    public void WaitForConnection(int millisecondsTimeout); 
    public void WaitForConnection(TimeSpan timeout); 
    public void WaitForDisconnection(); 
    public void WaitForDisconnection(int millisecondsTimeout); 
    public void WaitForDisconnection(TimeSpan timeout); 
    public bool AutoReconnect { get; set; } 
    public event ConnectionMessageEventHandler<TRead, TWrite> ServerMessage; 
    public event ConnectionEventHandler<TRead, TWrite> Disconnected; 
    public event PipeExceptionEventHandler Error; 
    } 
} 
+0

您是否需要在服務器和客戶端上使用.close和.dispose? – GamerJ5

+0

客戶端或服務器都沒有'Close()'函數。但是每個都有一個'Stop()'函數。 – Believe2014

+0

ManualResetEvent已關閉 - 您嘗試過嗎?看起來這是你產生的唯一線索。 – GamerJ5

回答

2

WindowsService繼承ServiceBase類有Dispose()功能關閉所有線程。這就是爲什麼我會遇到所有賽車錯誤。

我必須避免調用Dispose()函數,並用client.Close()svc.Close()函數替換它。 svc.Close()函數是我的自定義實現來停止和關閉命名管道服務器。

相關問題