Search code examples
c#multithreadingasynchronousservermultiplayer

Using Threading vs Asynchronous programming on a server


I am developing a little multiplayer game in my free time in C#.

I've read that Threading and Asynchronous programming are similar but which of them should I use when writing a server that is waiting for new connections and serving existing connections at the same time?

I took the asynchronous approach at first but then I read that it is mainly used for IO purposes. And that made me question if it's appropriate for a situation like this.

Thank you.


Solution

  • To be put simple, behind the scenes async/await can be threading - the framework decides based on your hints if the continuation task will run on the same thread or not, or to allocate a whole thread to a task if needed. There are threads and thread pools at the hands of the scheduler. But using Tasks is in general much more easy to manage than threads, and above all, much more performant. An OS thread is costly, a managed thread is not. Yes, it makes its best use in IO bound operations, but isn't network communication IO? Anyway, because of the above, if you use Tasks instead of treads you have the same synchronization tools at hands and more. Just as an example, both Kestrel and Katana servers are Task based.