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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T19:36:18+00:00 2026-06-10T19:36:18+00:00

I am looking to build an httpListener into a small server app. Whilst reading

  • 0

I am looking to build an httpListener into a small server app. Whilst reading up on it, i encountered the following code snippet in this question on stackoverflow

Public Class HTTPServer

Shared Listener As HttpListener = New HttpListener

Public Shared Sub Start()

    ServicePointManager.DefaultConnectionLimit = 500
    ServicePointManager.Expect100Continue = False
    ServicePointManager.MaxServicePoints = 500

    Listener.Prefixes.Add("http://localhost/")
    Listener.Start()

    For i As Integer = 1 To (System.Environment.ProcessorCount * 2)

        Dim NewThread As New System.Threading.Thread(AddressOf ListenerThread)
        NewThread.Priority = ThreadPriority.Normal
        NewThread.IsBackground = True
        NewThread.Start()

    Next

End Sub



Private Shared Sub ListenerThread()

    Dim SyncResult As IAsyncResult

    While True

        SyncResult = Listener.BeginGetContext(New AsyncCallback(AddressOf ListenerCallback), Listener)
        SyncResult.AsyncWaitHandle.WaitOne()

    End While

End Sub



Private Shared Sub ListenerCallback(ByVal StateObject As IAsyncResult)

    Dim Listener As HttpListener = DirectCast(StateObject.AsyncState, HttpListener)

    Dim Context As HttpListenerContext = Listener.EndGetContext(StateObject)
    Dim Request As HttpListenerRequest = Context.Request

    Dim Response As HttpListenerResponse = Context.Response

    Dim ResponseString As String = "OK"

    Dim Buffer As Byte() = System.Text.Encoding.UTF8.GetBytes(ResponseString)
    Response.ContentLength64 = Buffer.Length
    Dim OutputStream As System.IO.Stream = Response.OutputStream
    OutputStream.Write(Buffer, 0, Buffer.Length)

    OutputStream.Close()
    OutputStream.Dispose()

End Sub

End Class

Which seemed pretty simple, and seems much like the msdn example. However when testing it in a dummy project, i found a few things that confused me, for example UI objects can be accessed directly from the callback sub, which i thought should cause a cross threading exception.

To clarify, i modified this code slightly to run within the main form of a simple winforms project.

It seems i do not fully understand the code, for example AsyncWaitHandle.WaitOne() is completely new to me.

Could someone briefly walk me through this snippet please? Any help appreciated.

  • 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-06-10T19:36:19+00:00Added an answer on June 10, 2026 at 7:36 pm

    This snippet code looks like:

    1. It create a HttpListener and start linsening at the uri;
    2. It create some threads (number of System.Environment.ProcessorCount * 2) to send async request to listener try to get a context;
    3. Then the thread was blocked by call SyncResult.AsyncWaitHandle.WaitOne(), about the AsyncWaitHandle.WaitOne please check out Details of AsyncWaitHandle.WaitOne
    4. If some client request come in, the ListenerCallback() will be trigged, and it try to send response back to client
    5. Then go to the next round of loop.

    Because it called SyncResult.AsyncWaitHandle.WaitOne() to block that thread, it will get the same result with Synchronously call.

    In my opinion, it just returns a simple OK response, so we even don’t need any other threads. I will show you the code soon (My code will not work very well if we have heavy operations, and please don’t do this in form application.)

        static void Main(string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 500;
            ServicePointManager.Expect100Continue = false;
            ServicePointManager.MaxServicePoints = 500;
    
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:999/");
            listener.Start();
            listener.BeginGetContext(ListenerCallBack, listener);
    
    
            Console.ReadLine();
        }
    
        private static void ListenerCallBack(IAsyncResult result)
        {
            HttpListener httpListener = (HttpListener) result.AsyncState;
            // Call EndGetContext to complete the asynchronous operation.
            HttpListenerContext context = httpListener.EndGetContext(result);
            HttpListenerRequest request = context.Request;
            // Obtain a response object.
            HttpListenerResponse response = context.Response;
            // Construct a response. 
            string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            // Get a response stream and write the response to it.
            response.ContentLength64 = buffer.Length;
            System.IO.Stream output = response.OutputStream;
            output.Write(buffer,0,buffer.Length);
            // You must close the output stream.
            output.Close();
    
    
            // we call BeginGetContext() to send async request again for next coming client
            httpListener.BeginGetContext(ListenerCallBack, httpListener);
        }
    

    In C#5 and Net 4.5, we have sync method, it will much easier:

    static void Main(string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 500;
            ServicePointManager.Expect100Continue = false;
            ServicePointManager.MaxServicePoints = 500;
    
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:999/");
            listener.Start();
    
            while (true)
            {
                var t = listener.GetContextAsync();
                HttpListenerContext context = t.Result;
                HttpListenerRequest request = context.Request;
                // Obtain a response object.
                HttpListenerResponse response = context.Response;
                // Construct a response. 
                string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                // Get a response stream and write the response to it.
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                // You must close the output stream.
                output.Close();
            }
        }
    

    For your another question about “cross threading exception” for UI, you are right, the created new Thread will have a null value for SynchronizationContext.Current because it’s a thread pool thread, we need do a post() in form’s SynchronizationContext. Here are more information http://msdn.microsoft.com/en-us/magazine/gg598924.aspx and http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx.

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

Sidebar

Related Questions

I'm looking to build a dynamic website without bringing much extra server-side code/apps into
I'm looking to build an Android app(for learning) that searches for music files in
I'm looking to build a Rails app to do internal reporting (make charts or
I'm looking to build an ecommerce form using the PRG model. My question is
I am looking to build an app to be used on smartphones that can
We are looking to build a cube in Microsft SQL server analysis services but
I am looking to build out a custom modal view for an ipad app.
I am looking to build a button in my Android app which must contain:
I'm looking to build a VM into a game and was wondering if anyone
I'm looking to build a server with lots of tiny files delivered by an

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.