Skip to content

NetworkStream.BeginRead not conforming to the contract #69269

Closed
dotnet/dotnet-api-docs
#8332

Description

@fgao60

Description

In NetworkStream.BeginRead documentation, it states

When your application calls BeginRead, the system will wait until data is received or an error occurs, and then the system will use a separate thread to execute the specified callback method,

In reality, the specified callback could be invoked in the same thread if data was immediately available, which could cause StackOverflowException.

Reproduction Steps

The following program can be used to reproduce the problem, the steps in the program are:

  1. Create a server.
  2. Server starts to listen for a client.
  3. Create a client.
  4. Server waits for the client connection.
  5. Write Hello on the server side so that when the client begins to read, data is immediately available, flush the data.
  6. Print the ID of the current thread .
  7. Invoke NetworkStream.BeginRead on the client side, and set up the callback to print the current thread ID in the callback.
  8. Wait until the callback is finished.
using System;
using System.Text;
using System.Threading.Tasks;

namespace NetConsoleApp1
{
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;

    class NetworkStreamTest
    {
        public static async Task Main(string[] args)
        {
            int port = 3576;

            var listener = new TcpListener(IPAddress.Any, port);
            listener.Start();

            var waitForClient = listener.AcceptTcpClientAsync();
            var client = new TcpClient("localhost", port);
            var server = await waitForClient;

            // Write Hello first on the server so that when the client begins
            // read, data is immediately available.
            var serverStream = server.GetStream();
            string hello = "Hello";
            serverStream.Write(Encoding.ASCII.GetBytes(hello), 0, hello.Length);
            await serverStream.FlushAsync();
            Console.WriteLine($"Server sent: {hello}");

            // Print NetworkStream.BeginRead thread ID
            Console.WriteLine(
                $"NetworkStream.BeginRead is invoked in thread {Thread.CurrentThread.ManagedThreadId}");

            bool callbackInvoked = false;
            NetworkStream clientStream = client.GetStream();
            byte[] bytes = new byte[100];
            var asyncResult = clientStream.BeginRead(
                bytes,
                0,
                100,
                (IAsyncResult result) =>
                {
                    int numRead = clientStream.EndRead(result);

                    // Print the ID of the thread where the callback is running.
                    Console.WriteLine(
                        $"Callback is invoked in thread {Thread.CurrentThread.ManagedThreadId}");
                    Console.WriteLine($"Client received: {Encoding.ASCII.GetString(bytes, 0, numRead)}");
                    callbackInvoked = true;
                },
                state: null);

            Console.WriteLine(
                "NetworkStream.BeginRead is completed" +
                $" synchronously: {asyncResult.CompletedSynchronously}");

            while (!callbackInvoked)
            {
                return;
            }
        }
    }
}

Expected behavior

The callback should be invoked in a different thread than the thread where NetworkStream.BeginRead is invoked.

Actual behavior

Output:

Server sent: Hello
NetworkStream.BeginRead is invoked in thread 5
Callback is invoked in thread 5
Client received: Hello
NetworkStream.BeginRead is completed synchronously: True

The callback is invoked in the same thread.

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

No response

Activity

  1. ghost added
    untriaged
    on May 12, 2022
  2. stephentoub commented on May 12, 2022

    @stephentoub
    Member

    The docs here are wrong. This has never been the contractual behavioral. Tweaking the docs would be fine.

    In reality, the specified callback could be invoked in the same thread if data was immediately available, which could cause StackOverflowException.

    This is why IAsyncResult includes the CompletedSynchronously property. A conforming APM consumer will check CompletedSynchronously in both the callback and the caller, and should do the follow-up work in the caller if CompletedSynchronously is true and in the callback if CompletedSynchronously is false. This is one of the many things that made the APM / IAsyncResult pattern difficult to implement and consume. IAsyncResult and the associated Begin/End methods are all now considered legacy.

  3. fgao60 commented on May 12, 2022

    @fgao60
    Author

    I agree we could check CompletedSynchronously property, however recently we ran into StackOverflowException in .NET 6 with our legacy code, which never happened before with previous versions of .NET core or .NET framework. We dug into it and found that

    We would like to get more information about this difference.

  4. KalleOlaviNiemitalo commented on May 13, 2022

    @KalleOlaviNiemitalo

    Socket.BeginReceive and other such methods were changed to use TaskToApm rather than OverlappedAsyncResult, in #43886 for #43845. Perhaps that is not the information you seek, because I don't see any comments about recursive synchronous completion in either of those.

  5. fgao60 commented on May 13, 2022

    @fgao60
    Author

    This seems to me a regression. Would .NET consider adding the protection logic back?

  6. wfurt commented on May 13, 2022

    @wfurt
    Member

    It is highly unlikely we would go back @fgao60. While there may be observable difference, as @stephentoub mentioned this was never part of the contract. We cannot guarantee just any observers behavior. APM pattern is difficult to maintain and the APM->Task changes were made to make the code more maintainable.

  7. CarnaViire commented on May 19, 2022

    @CarnaViire
    Member

    Triage: we should fix the docs in 7.0

  8. removed
    untriaged
    on May 19, 2022
  9. added this to the 7.0.0 milestone on May 19, 2022
  10. added
    documentation
    on May 19, 2022
  11. self-assigned this
    on Jun 2, 2022
  12. added a commit that references this issue on Aug 24, 2022
  13. added a commit that references this issue on Aug 31, 2022
    62ac468
  14. antonfirsov commented on Aug 31, 2022

    @antonfirsov
    Contributor

    This has been addressed by a documentation update dotnet/dotnet-api-docs#8332, we have no plans to bring back the legacy behavior.

  15. ghost locked as resolved and limited conversation to collaborators on Oct 3, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-System.Net.Socketsdocumentation

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions