I have been having playing with implementing some socket code to see if it fits my needs and so use the sample code @spender kindly added to this question.
If I run this on the main thread it works as expected but when I invoke it on a background thread it never gets awoken from its sleep when a client attempts to connect, my thread spawn is as below:
_Thread = new Thread(new ThreadStart(StartListening));
_Thread.Name = "ThreadForSocket";
_Thread.IsBackground = true;
_Thread.Start();
private void StartListening()
{
new AsyncSocketListener().StartListening(InitializeEndPoint());
}
public class AsyncSocketListener : IDisposable
{
public void StartListening(IPEndPoint endPoint)
{
try
{
var socket = new Socket(endPoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(endPoint);
socket.Listen(10);
while (true)
{
string info = string.Format("{0} Waiting for a connection...", DateTime.Now.ToString("HH:mm.ss"));
Controller.StatusSignal.Reset();
Console.WriteLine(info);
Debug.WriteLine(info);
socket.BeginAccept(new AsyncCallback(SocketListener.AcceptCallback), socket);
Controller.StatusSignal.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("Closing the listener...");
}
The thread is still present in the Threads Window and is in the expected state so I'm at a loss as to why it refuses to wake up on client connection.
Should that be possible? I read the socket msdn page and it appears to suggest it should be OK for a background thread.