C# Task 或 Thread 用于多个侦听器

C# Task, or Thread for multiple listeners

我正在尝试将用 Python/Tornado 编写的游戏服务器移植到 C#。我需要 2 个 TCP 异步侦听器(具有多个客户端)和主游戏循环。有什么好的处理方法?

目前我找到了两种方法:

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

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

Task.WaitAll(gameListenerTask, lobbyListenerTask);

或者:

        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();

还有小二的问题。如果我阅读我正在使用:

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

读取的字节总是放在缓冲区的开头?

要回答您的问题,您需要知道任务和线程之间的区别。

this 个问题中“Mitch Wheat”的回答如下:

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.

根据这个答案,你应该使用任务,就像“Sreemat”说的那样。任务注定要使用“异步”操作。

你的小问题: 基于“BeginReceive”方法的description,我认为你是对的。