I implemented class that serves as TcpCLient server. Looks like this:
{
[Export]
public class MessageListener
{
private readonly TcpListener tcpListener;
private readonly Thread listenThread;
private DataRepository DataRepository { get; set; }
private IEventAggregator EventAggregator { get; set; }
[ImportingConstructor]
public MessageListener(DataRepository dataRepository, IEventAggregator eventAggregator)
{
this.DataRepository = dataRepository;
this.EventAggregator = eventAggregator;
// TODO: Need to put proper Port number
this.tcpListener = new TcpListener(IPAddress.Any, 3000);
this.listenThread = new Thread(this.ListenForClients);
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
// blocks until a client has connected to the server
var client = this.tcpListener.AcceptTcpClient();
// create a thread to handle communication with connected client
var clientThread = new Thread(this.HandleClientComm);
clientThread.Start(client);
}
}
This listener imported in my Shell view model. Works good.
When I close WPF window – MEF won’t dispose this object. Windows closes but process still running. How do I properly shutdown this “server”? It waits for var client..
The process won’t exit until all foreground threads complete.
In this case, since you’re starting a new thread, you can just make it a background thread:
Background threads won’t keep the process alive.