簡體   English   中英

如何確保測試啟動的所有線程在完成之前停止

[英]How to make sure that all the threads started by the test(s) are stopped before completion

我正在構建一個使用命名管道與其他進程通信的Windows服務。 我對命名管道通信的單元測試是拋出此錯誤消息4次:

System.AppDomainUnloadedException:嘗試訪問已卸載的AppDomain。 如果測試開始一個線程但沒有停止它,就會發生這種情況。 確保測試啟動的所有線程在完成之前停止。

這是我的單元測試:

    [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();
    }

如何在單元測試停止之前停止所有線程?

謝謝


更新:

命名管道客戶端沒有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;
  }
}

我的WindowsService繼承了ServiceBase類,它具有Dispose()函數來關閉所有線程。 這就是為什么我得到所有賽車錯誤。

我必須避免調用Dispose()的功能,取而代之的是client.Close()svc.Close()函數。 svc.Close()函數是我的自定義實現,用於停止和關閉命名管道服務器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM