Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3488408
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T11:16:02+00:00 2026-05-18T11:16:02+00:00

I need to read from NetworkStream which would send data randomly and the size

  • 0

I need to read from NetworkStream which would send data randomly and the size of data packets also keep varying. I am implementing a multi-threaded application where each thread would have its own stream to read from. If there is no data on the stream, the application should keep waiting for the data to arrive. However, if the server is done sending data and has terminated the session, then it should exit out.

Initially I had utilised the Read method to obtain the data from the stream, but it used to block the thread and kept waiting until data appeared on the stream.

The documentation on MSDN suggests,

If no data is available for reading,
the Read method returns 0. If the
remote host shuts down the connection,
and all available data has been
received, the Read method completes
immediately and return zero bytes.

But in my case, I have never got the Read method to return 0 and exit gracefully. It just waits indefinitely.

In my further investigation, I came across BeginRead which watches the stream and invokes a callback method asynchronously, as soon as it receives the data. I have tried to look for various implementations using this approach as well, however, I was unable to identify when would using BeginRead be beneficial as opposed to Read.

As I look at it, BeginRead has just the advantage of having the async call, which would not block the current thread. But in my application, I already have a separate thread to read and process the data from stream, so that wouldn’t make much difference for me.

  • Can anyone please help me understand the Wait and Exit mechanism for
    BeginRead and how is it different from Read?

  • What would be the best way to implement the desired functionality?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T11:16:02+00:00Added an answer on May 18, 2026 at 11:16 am

    I use BeginRead, but continue blocking the thread using a WaitHandle:

    byte[] readBuffer = new byte[32];
    var asyncReader = stream.BeginRead(readBuffer, 0, readBuffer.Length, 
        null, null);
    
    WaitHandle handle = asyncReader.AsyncWaitHandle;
    
    // Give the reader 2seconds to respond with a value
    bool completed = handle.WaitOne(2000, false);
    if (completed)
    {
        int bytesRead = stream.EndRead(asyncReader);
    
        StringBuilder message = new StringBuilder();
        message.Append(Encoding.ASCII.GetString(readBuffer, 0, bytesRead));
    }
    

    Basically it allows a timeout of the async reads using the WaitHandle and gives you a boolean value (completed) if the read was completed in the set time (2000 in this case).

    Here’s my full stream reading code copied and pasted from one of my Windows Mobile projects:

    private static bool GetResponse(NetworkStream stream, out string response)
    {
        byte[] readBuffer = new byte[32];
        var asyncReader = stream.BeginRead(readBuffer, 0, readBuffer.Length, null, null);
        WaitHandle handle = asyncReader.AsyncWaitHandle;
    
        // Give the reader 2seconds to respond with a value
        bool completed = handle.WaitOne(2000, false);
        if (completed)
        {
            int bytesRead = stream.EndRead(asyncReader);
    
            StringBuilder message = new StringBuilder();
            message.Append(Encoding.ASCII.GetString(readBuffer, 0, bytesRead));
    
            if (bytesRead == readBuffer.Length)
            {
                // There's possibly more than 32 bytes to read, so get the next 
                // section of the response
                string continuedResponse;
                if (GetResponse(stream, out continuedResponse))
                {
                    message.Append(continuedResponse);
                }
            }
    
            response = message.ToString();
            return true;
        }
        else
        {
            int bytesRead = stream.EndRead(asyncReader);
            if (bytesRead == 0)
            {
                // 0 bytes were returned, so the read has finished
                response = string.Empty;
                return true;
            }
            else
            {
                throw new TimeoutException(
                    "The device failed to read in an appropriate amount of time.");
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.