Im doing some sockets programming that will eventually go into a windows service. For testing purposes im using a console application. Im a little puzzled because the BeginAcceptTcpClient or the Task.WaitAll does not wait and the console application just ends. If i add a Console.ReadLine at the end of main , everything works ok. With some slight modifications in Main it also works when i run it as as service. Why doesnt the Task.WaitAll wait until all tasks in the console application has finished and why doesnt the BeginAcceptTcpClient halt and wait for connection in console but works perfectly when i run it in a service.
static void Main(string[] args)
{
listener = new TcpListener(IP_ADDRESS, Port);
listener.Start();
var tasks = new List<Task>();
Task task = Task.Factory.StartNew(() => AcceptClient(listener),TaskCreationOptions.LongRunning);
tasks.Add(task);
Task.WaitAll(tasks.ToArray());
}
private static void AcceptClient(TcpListener tcpListener)
{
Task<TcpClient> acceptTcpClientTask = Task.Factory.FromAsync<TcpClient>(tcpListener.BeginAcceptTcpClient, tcpListener.EndAcceptTcpClient, tcpListener);
acceptTcpClientTask.ContinueWith(task => { OnAcceptConnection(task.Result); AcceptClient(tcpListener); }, TaskContinuationOptions.OnlyOnRanToCompletion);
}
This is the basis of asynchronous programming. Use AccesptTcpClient to wait for the result.
Begin* functions return immediately. You can specify a callback to be called when result arrives.