Repository navigation
Closed
dotnet/dotnet-api-docs
#8332Closed
Copy link
Labels
area-System.Net.SocketsdocumentationDocumentation bug or enhancement, does not impact product or test code
Milestone
Description
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:
- Create a server.
- Server starts to listen for a client.
- Create a client.
- Server waits for the client connection.
- Write
Helloon the server side so that when the client begins to read, data is immediately available, flush the data. - Print the ID of the current thread .
- Invoke
NetworkStream.BeginReadon the client side, and set up the callback to print the current thread ID in the callback. - 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
Metadata
Metadata
Assignees
Labels
area-System.Net.SocketsdocumentationDocumentation bug or enhancement, does not impact product or test code
Activity
stephentoub commentedon May 12, 2022
The docs here are wrong. This has never been the contractual behavioral. Tweaking the docs would be fine.
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.
fgao60 commentedon May 12, 2022
I agree we could check
CompletedSynchronouslyproperty, however recently we ran intoStackOverflowExceptionin .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.NET framework tries to avoid stack overflow by forcing the callback to be run on a threadpool if the stack size >= 50 , the logic is here.
http://referencesource.microsoft.com/#System/net/System/Net/_LazyAsyncResult.cs,406
NET 3 and 5 still have the same logic
NET 6 instead has a very different logic around
NetworkStream.BeginReadwhich ends up calling https://source.dot.net/#System.Net.Requests/TaskToApm.cs,96the stack size >= 50 logic is no longer there. Instead the callback is always invoked synchronously.
We would like to get more information about this difference.
KalleOlaviNiemitalo commentedon May 13, 2022
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.
fgao60 commentedon May 13, 2022
This seems to me a regression. Would .NET consider adding the protection logic back?
wfurt commentedon May 13, 2022
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.
CarnaViire commentedon May 19, 2022
Triage: we should fix the docs in 7.0
Fix remark on NetworkStream.BeginRead
Update Socket & NetworkStream APM docs (#8332)
antonfirsov commentedon Aug 31, 2022
This has been addressed by a documentation update dotnet/dotnet-api-docs#8332, we have no plans to bring back the legacy behavior.