Pregunta

I am building a very simple server that has to use named pipes in .NET, and will be ran behind a Windows Forms GUI. I have been able to implement a ServiceHost in a 'Server' class (below) and communicate with it using a 'Client' class. The problem I am having is figuring out the proper way to close the ServiceHost that is running on a thread, as well as disposing of the thread when the form is closed. I am new to threads and named pipes, so be nice!


This is the form which starts my server/client:

public partial class MyForm : Form
{
    Thread server;
    Client client;

    public MyForm()
    {
        InitializeComponent();

        server = new Thread(() => new Server());
        server.Start();

        client = new Client();
        client.Connect();
    }
}

private void MyForm_FormClosed(object sender, FormClosedEventArgs e)
{
    // Close server thread and disconnect client.
    client.Disconnect();

    // Properly close server connection and dispose of thread(?)
}



And here is the Server class:

class Server : IDisposable
{
    public ServiceHost host;
    private bool disposed = false;

    public Server()
    {
        host = new ServiceHost(
            typeof(Services),
                new Uri[]{
                new Uri("net.pipe://localhost")
            });

        host.AddServiceEndpoint(typeof(IServices), new NetNamedPipeBinding(), "GetData");
        host.AddServiceEndpoint(typeof(IServices), new NetNamedPipeBinding(), "SubmitData");
        host.Open();

        Console.WriteLine("Server is available.");
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    { 
        if(!this.disposed)
        {
            if(disposing)
            {
                host.Close();
            }

            disposed = true;
        }
    }

    ~Server()
    {
        Dispose(false);
    }
}




Is using IDisposable a good approach to this, and how do I go about calling Dispose() when I'm finished with my thread?

¿Fue útil?

Solución

You are making this harder than it needs to be.

  1. Don't create a thread to start ServiceHost. ServiceHost will manage its own threads internally for the service calls. There's no advantage to creating a new thread just to start the ServiceHost. Also your client Connect() call won't succeed until the ServiceHost is initialized and running. So there's required synchronization between server.Start() and client.Connect(). The new thread isn't saving you anything.

  2. Do not do Finalizers in C# unless you have a very good reason. ~Server() is a bad idea.

So get rid of the Server class entirely. The wrapper isn't buying you anything (unless you are doing configuration management that isn't shown in the posted code).

Create the service host in MyForm() and call host.Close() in MyForm_FormClosed(). Done.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top