2
\$\begingroup\$

I'm not really super experienced async/await and working with tasks, so I thought I'd ask for some other opinions.

I'm working with code written by someone else that establishes a TCP connection. It works most of the time. But sometimes it just doesn't, and the connection gets dropped and we don't know about it.

My first suspicion is that it's calling Task.Run(() =>, which goes on to call a method that calls Task.Factory.StartNew(async () =>, which in turn goes to call await Task.Run(() =>.

Does this code look ok to more experienced eyes? Is there anything that could be done to improve it?

public bool StartListening(string ipAddress, int port)
{
    Task.Run(() =>
    {
        _canceller = new CancellationTokenSource();

        _backingTcpListener = new TcpListener(IPAddress.Parse(ipAddress), port);
        _backingTcpListener.Start();

        WaitForConnections(_canceller.Token);
    });

    return true;
}

private void WaitForConnections(CancellationToken cancelToken)
{
    Task.Factory.StartNew(async () =>
    {
        while (!cancelToken.IsCancellationRequested)
        {
            var inner = await Task.Run(() =>
            {
                try
                {
                    return _backingTcpListener.AcceptTcpClient();
                }
                catch (SocketException)
                {
                    // this will be caused by StopListeningAsync
                    return null;
                }
            }, cancelToken);

            if (inner == null)
            {
                // null will be returned when the SocketException is caught above
                return;
            }

            var outer = new TcpSocketClient(inner, _bufferSize);

            var args = new TcpSocketConnectionReceivedEventArgs(outer);

            ConnectionReceived?.Invoke(args);
        }
    }, cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.