Search code examples
c#multithreadingasynchronousmonotornado

C# Task, or Thread for multiple listeners


I am trying to port my game server written in Python/Tornado to C#. I need 2 TCP async listeners (with multiple clients), and main game loop. What is a good way to handle this?

I found two ways for now:

var gameListenerTask = Task.Run(() => {
    //Run listener and wait
});

var lobbyListenerTask = Task.Run(() => {
    // Run other listener.
});

Task.WaitAll(gameListenerTask, lobbyListenerTask);

Or:

        var gameServiceTask = new Thread(() =>
        {
            var gameService = new GameService();
            gameService.Start(15006);
        });

        var lobbyServiceTask = new Thread(() =>
        {
            var lobbyService = new LobbyService();
            lobbyService.Start(15007);
        });


        gameServiceTask.Start();
        lobbyServiceTask.Start();

And small second question. If I read I am using:

handler.BeginReceive(client.Buffer, 0, Settings.ClientBufferSize, 
    SocketFlags.None, new AsyncCallback(client.ReadData), client);

Readed bytes will be always put at the beginning of buffer?


Solution

  • To answer your question, you need to know the difference between tasks and threads.

    In this questions "Mitch Wheat" answers that question as follow:

    A task is something you want done.

    A thread is one of the many possible workers which performs that task.

    In .NET 4.0 terms, a Task represents an asynchronous operation. Thread(s) are used to complete that operation by breaking the work up into chunks and assigning to separate threads.

    Based on this answer, you should use tasks, like "Sreemat" says. Tasks are predestined for using "async" operations.

    Your small question: Based on the description of the "BeginReceive" method, I think you are right.