The await task;
in your Main
won't compile; you'll have to use task.Wait();
if you want to block on it.
Also, you should use Task.Run
instead of Task.Factory.StartNew
in asynchronous programming.
Creating new Task does not necessarily mean new thread, but is this the right way?
You certainly can start up separate tasks (using Task.Run
). Though you don't have to. You could just as easily call a separate async
method to handle the individual socket connections.
There are a few problems with your actual socket handling, though. The Connected
property is practically useless. You should always be continuously reading from a connected socket, even while you're writing to it. Also, you should be writing "keepalive" messages or have a timeout on your reads, so that you can detect half-open situations. I maintain a TCP/IP .NET FAQ that explains these common problems.
I really, strongly recommend that people do not write TCP/IP servers or clients. There are tons of pitfalls. It would be far better to self-host WebAPI and/or SignalR, if possible.