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?