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 4565292
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T18:37:21+00:00 2026-05-21T18:37:21+00:00

I want to use NetworkStream (or maybe Socket ) to read/write TCP connections. I

  • 0

I want to use NetworkStream (or maybe Socket) to read/write TCP connections. I want to use non-blocking operations so that I don’t have to deal with several threads, or deal with the issue of how to stop the program if some threads might be halted on blocking network operations.

The documentation of NetworkStream.Read implies it is non-blocking (“If no data is available for reading, the Read method returns 0”), so I guess I don’t need async callbacks for reading… right?

But what about writing? Well, Microsoft has one of its usual low-quality tutorials on this subject, and they propose writing a cumbersome AsyncCallback method for every operation. What’s the point of the code inside this callback?

client.BeginSend(byteData, 0, byteData.Length, SocketFlags.None,
                 new AsyncCallback(SendCallback), client);
    ...
private static void SendCallback(IAsyncResult ar)
{
    try {
        Socket client = (Socket)ar.AsyncState;

        int bytesSent = client.EndSend(ar);

        Console.WriteLine("Sent {0} bytes to server.", bytesSent);
        // Signal that all bytes have been sent.

        sendDone.Set();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

The documentation of AsyncCallback says it’s “a callback method that is called when the asynchronous operation completes”. If the operation is completed already, why do we have to call Socket.EndSend(IAsyncResult)? Meanwhile, the documentation of NetworkStream.BeginWrite says “You must create a callback method that implements the AsyncCallback delegate and pass its name to the BeginWrite method. At the very minimum, your state parameter must contain the NetworkStream.”

But why “must” I? Can’t I just store the IAsyncResult somewhere…

_sendOp = client.BeginSend(message, 0, message.Length, SocketFlags.None, null, null);

…and periodically check whether it’s finished?

if (_sendOp.IsCompleted)
    // start sending the next message in the queue

(I know this implies polling, but it will be in a server that is expected to be active most of the time, and I’m planning some Thread.Sleeps when idle.)

Another issue. The messages I’m sending are broken up into a header array and a body array. Can I can issue two BeginWrites in a row?

IAsyncResult ar1 = _stream.BeginWrite(header, 0, header.Length, null, null);
IAsyncResult ar2 = _stream.BeginWrite(msgBody, 0, msgBody.Length, null, null);

Also, any opinions are welcome about whether to use Socket or NetworkStream.

  • 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-21T18:37:21+00:00Added an answer on May 21, 2026 at 6:37 pm

    I don’t have any experience with NetworkStream, but I can say this about asynchronous Socket operations:

    • End* needs to be called when the operation completes because this cleans up OS resources used by the asynchronous operation and allows you to get the result of the operation (even if that result is just whether it succeeded or failed). MSDN has a good overview of this common asynchronous pattern.
    • You are not required to pass any particular object as the state parameter. When that documentation was written, passing it was the easiest way to keep the object in scope for the completion delegate. These days, with lambda expressions, that practice is not nearly as common.
    • You can queue up writes to the socket, and under most conditions this will work. It is possible, though, that one of the writes will only partially complete (I’ve never seen this happen, but it is theoretically possible). I did this for years but no longer recommend it.

    I do recommend using completion delegates instead of polling. If you want an easier-to-use wrapper, you could try Nito.Async.Sockets, which wraps the Begin/End operations and serializes them all through a single thread (e.g., a UI thread).

    P.S. If you want to stop a blocking operation, you can close the socket from another thread, which will cause the operation to complete with an error. However, I don’t recommend using blocking socket operations.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to use Powershell to write some utilities, leveraging our own .NET components
I want to use the MultipleLookupField control in a web page that will run
I want to create SOCKET chat(server + clients) with private messaging. When client write
I have a byte array that I am reading in from a NetworkStream. The
I want use math operations in XAML code but I dont know how?
How to access to file in another domain by ajax (I don't want use
I want to use a temp directory that will be unique to this build.
I want use $.ajax to read some infomation from xml file,here is my js
i want use XmlSampleGenerator API in my project. i don't know how to add
I want to port my linux code to windows. I don't want use cygwin

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.