jeudi 28 juillet 2016

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

I am building a windows service that communicates with other processes using named pipe. My unit test for the named pipe communication is throwing this error message 4 times:

System.AppDomainUnloadedException: Attempted to access an unloaded AppDomain. This can happen if the test(s) started a thread but did not stop it. Make sure that all the threads started by the test(s) are stopped before completion.

Here's my unit test:

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

How do I make all threads stop before my unit test stops?

Thanks

Aucun commentaire:

Enregistrer un commentaire