Link to home
Create AccountLog in
.NET Programming

.NET Programming

--

Questions

--

Followers

Top Experts

Avatar of peddle
peddle

Socket.BeginReceive issue with thread blocking
Hi All,
I am having trouble understanding the correct functionality of BeginReceive in the .NET socket object. According to MSDN, BeginReceive will return immediately and the callback function will be run on a separate thread when data is received.
However, I have found that blocking the main thread also causes the receive process to be blocked. From the code below, I would expect to see the following output:
"Listening"
"Data received"
"Return"
This would indicate that the data is correctly received while the main thread sleeps (in real life, it would be doing other work). However, no data is received while the thread sleeps, instead all calls to OnDataReceived only occur after the sleep has ended.
Could anyone shed any light on this?
Many thanks,
Samuele Armondi
public class Client
    {
        private Socket socket;
        private AutoResetEvent autoResetEvent;
        private IPEndPoint serverEndPoint;
        private byte[] buffer;
 
        public bool Connect()
        {
            //connection code
            socket.Connect(serverEndPoint);
                       
            //start listening for data
            Debug.Print("Listening");
            socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
 
            Thread.Sleep(1000);
            Debug.Print("Return");
        }
 
        //Async method called when data is received.
        private void OnDataReceived(IAsyncResult res)
        {
            //handle data
            Debug.Print("Data received.");
            
            //carry on receiving
            socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);            
        }
    }

Open in new window

Zero AI Policy

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of MogalManicMogalManic🇺🇸

How are you creating the socket?  If you are using the SocketInformation class there is an option in SocketInformationOptions to create a NonBlocking socket.

I made some simple modifictaions to your sample and it worked for me.
  1)  Increased the delay (one second might not be long enough):
        Debug.Print("Sleeping");
        do {
            Thread.Sleep(1000);  //Keep sleeping until async result is processed
        } while (!Done);
        Debug.Print("Return");
   2) did not receive again if aync result was complete also set the Done flag:
    private void OnDataReceived(IAsyncResult res)
    {
        //handle data
        Debug.Print("Data received:"+Encoding.UTF8.GetString(buffer));

        if (res.IsCompleted == false)
        {
            //carry on receiving
            socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
        }
        Debug.Print("All Done");
        Done = true;
    }

ASKER CERTIFIED SOLUTION
Avatar of peddlepeddle

ASKER

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.
Create Account

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.

.NET Programming

.NET Programming

--

Questions

--

Followers

Top Experts

The .NET Framework is not specific to any one programming language; rather, it includes a library of functions that allows developers to rapidly build applications. Several supported languages include C#, VB.NET, C++ or ASP.NET.