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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T13:58:31+00:00 2026-05-28T13:58:31+00:00

I’m running the following piece of code which uses a delegate to return an

  • 0

I’m running the following piece of code which uses a delegate to return an asynchronous Network Stream:

static void Main(string[] args)
{
    NetworkStream myNetworkStream;
    Socket socket;
    IPEndPoint maxPort = new IPEndPoint(IPAddress.Parse("xxx.xxx.xxx.xxx"), xxxx);

    socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    socket.Connect(maxPort);

    myNetworkStream = new NetworkStream(socket);

    byte[] buffer = new byte[1024];
    int offset = 0;
    int count = 1024;

    string Command = "LOGIN,,,xxxx\n";
    ASCIIEncoding encoder = new ASCIIEncoding();

    myNetworkStream.BeginRead(buffer, offset, count, new AsyncCallback(OnBeginRead), myNetworkStream);
    myNetworkStream.Write(encoder.GetBytes(Command), 0, encoder.GetByteCount(Command));

    while (true) { }
}

public static void OnBeginRead(IAsyncResult ar)
{
    NetworkStream ns = (NetworkStream)ar.AsyncState;
    int bufferSize = 1024;
    byte[] received = new byte[bufferSize];

    ns.EndRead(ar);

    int read;

    while (true)
    {
        if (ns.DataAvailable)
        {
            string result = String.Empty;

            read = ns.Read(received, 0, bufferSize);
            result += Encoding.ASCII.GetString(received);
            received = new byte[bufferSize];

            result = result.Replace(" ", "");
            result = result.Replace("\0", "");
            result = result.Replace("\r\n", ",");

            Console.WriteLine(result);
        }
    }
}

It works, but my CPU usage is through the roof (50% on an Intel Core i3), so obviously I’m doing it wrong, but how so?

Thanks

  • 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-28T13:58:31+00:00Added an answer on May 28, 2026 at 1:58 pm

    You’re only reading the very first bytes asynchronously, afterwards you end up in an infinite loop with sync read operations in your OnBeginRead method (which is a confusing name BTW). At the same time, those first bytes are discarded in your current code.

    You need to process the data after EndRead (which is a function returning how many bytes were read into the buffer in this async operation), and then start another async read with BeginRead and return (there is no looping in the async code!).

    Edited to add a sample showing how async reading would work:

    internal class StreamHelper {
        private readonly NetworkStream stream;
        private readonly byte[] buffer = new byte[1024];
    
        public StreamHelper(Socket socket) {
            stream = new NetworkStream(socket);
        }
    
        public NetworkStream Stream {
            get {
                return stream;
            }
        }
    
        public byte[] Buffer {
            get {
                return buffer;
            }
        }
    }
    
    private static void Main(string[] args) {
        IPEndPoint maxPort = new IPEndPoint(IPAddress.Parse("xxx.xxx.xxx.xxx"), 100);
    
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        socket.Connect(maxPort);
    
        StreamHelper helper = new StreamHelper(socket);
        helper.Stream.BeginRead(helper.Buffer, 0, helper.Buffer.Length, StreamReadCallback, helper);
    
        string Command = "LOGIN,,,xxxx\n";
        byte[] bytes = Encoding.ASCII.GetBytes(Command);
        // note: the write isn't async, but should maybe be converted as well
        helper.Stream.Write(bytes, 0, bytes.Length);
    
        Console.ReadLine(); // wait for a return key press
    }
    
    private static void StreamReadCallback(IAsyncResult ar) {
        StreamHelper helper = (StreamHelper)ar.AsyncState;
        // note: EndRead will throw an exception if something went wrong - you should deal with that
        int bytesRead = helper.Stream.EndRead(ar);
        if (bytesRead > 0) {
            string charsRead = Encoding.ASCII.GetString(helper.Buffer, 0, bytesRead);
            Console.Write(charsRead);
            helper.Stream.BeginRead(helper.Buffer, 0, helper.Buffer.Length, StreamReadCallback, helper);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am currently running into a problem where an element is coming back from
I have a French site that I want to parse, but am running into
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this

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.