.NET - 带有async / await的套接字服务器

时间:2016-10-21 15:22:34

标签: c# sockets asynchronous async-await

我正在用C#编写简单的套接字服务器。我们的想法是尽可能简单,因为沟通不会很繁重。我在套接字异步调用上使用了一些TAP / APM模式,所以代码现在看起来像这样:

    public async Task StartListening()
    {
        try
        {
            var endpoint = new IPEndPoint(IPAddress.Loopback, Port);

            using (Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                Socket.Bind(endpoint);
                Socket.Listen(Limit);
                while (!Shutdown)
                {
                    // await till we get the connection - let the main thread/caller continue (I expect this loop to continue in separate thread after await)
                    var socket = await Socket.AcceptAsync().ConfigureAwait(false);

                    var state= new ClientStateObject(socket, id);
                    // do not await for receive - continue to listen for connections
                    Receive(socket, state);
                }
            }
        }
        catch (Exception ex)
        {
            // handle errors via callbacks
        }
    }

    private async void Receive(Socket socket, ClientStateObject state)
    {
        try
        {
            while (!Shutdown)
            {
                var bytes = await socket.ReceiveAsync(state).ConfigureAwait(false);

                var readResult = state.Read(bytes);
                if (readResult == CloseConn)
                {
                    // close connection

                    return;
                }

                if (readResult == Completed)
                {
                    // process the message

                    state.Reset();
                }
            }
        }
        catch (Exception ex)
        {
            // handle errors via callbacks
        }
    }

此代码似乎在开发版本中运行良好,但有时在发布模式下表现很奇怪。我假设这可能与竞争条件或与线程和async / await相关的事情有关。有没有人看到上述代码可能出现的问题?

为了清楚起见,AcceptAsync / ReceiveAsync是套接字方法的包装器,用于返回任务。

0 个答案:

没有答案