'Detecting when a TcpClient shuts down?

I have a server which I'm trying to detect when a TcpClient disconnects, the client does this gracefully but I can't seem to find a way to detect.

What have I tried?

I've added a ping pong method, but this doesn't catch it instantly, I've read that if bytes received = 0 then the client is disconnected? I've added an else statement to catch that but its executed about 100 times a second?

I've also tried "polling" in the read loop, but this also always evaluates to true?

if (_client.Client.Poll(1000, SelectMode.SelectRead) && _client.Client.Available == 0)
{
    Console.WriteLine("disconnected");
}

I'm a little stuck here, I've read numerous SO posts, a lot are old and don't take the new asynchronous code in to consideration, a lot seem to be using socket also.

Listening block:

protected async Task StartListening(CancellationToken cancellationToken)
{
    try
    {
        while (true)
        {
            cancellationToken.ThrowIfCancellationRequested();
            
            var bytes = await _client.Client.ReceiveAsync(_buffer, SocketFlags.None);

            if (bytes > 0)
            {
                await OnReceivedAsync(bytes);
            }
            else
            {
                _logger.LogWarning("Client disconnected?");
            }

            Thread.Sleep(100);
        }
    }
    catch (Exception e)
    {
        _logger.LogError(e.ToString());
        Dispose();
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source