.NET で名前付きパイプを使用する必要があり、Windows フォーム GUI の背後で実行される非常に単純なサーバーを構築しています。「サーバー」クラス (以下) に ServiceHost を実装し、「クライアント」クラスを使用して通信することができました。私が抱えている問題は、フォームが閉じられたときにスレッドを破棄するだけでなく、スレッドで実行されている ServiceHost を閉じる適切な方法を見つけ出すことです。スレッドと名前付きパイプは初めてなので、よろしくお願いします。
これは私のサーバー/クライアントを起動するフォームです:
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(?)
}
サーバークラスは次のとおりです。
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);
}
}
IDisposable を使用することはこれに対する適切なアプローチですか? また、スレッドの処理が終了したときに Dispose() を呼び出すにはどうすればよいですか?