我正在构建一个非常简单的服务器,它必须在.NET中使用命名管道,并将在Windows窗体GUI之后运行.我已经能够在'Server'类(下面)中实现ServiceHost,并使用'Client'类与它进行通信.我遇到的问题是找出关闭在线程上运行的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(?)
}
Run Code Online (Sandbox Code Playgroud)
这是Server类:
class Server : IDisposable
{
public ServiceHost host;
private bool disposed = false;
public Server()
{
host = new ServiceHost(
typeof(Services),
new …Run Code Online (Sandbox Code Playgroud)