R
R
Roman Gamretsky2014-09-28 11:41:44
Computer networks
Roman Gamretsky, 2014-09-28 11:41:44

How to implement asynchronous listening on HttpListener C#?

Tell me how to implement listening to http requests in the following code without slowing down the work of the main program?

HttpListener listener = new HttpListener();
        StringBuilder log = new StringBuilder();
        string path;
        private async void button1_Click(object sender, EventArgs e)
        {
            listener.Prefixes.Add("http://localhost:8080/");

            listener.Start();
            //listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            if (listener.IsListening)
            {
                button1.Enabled = false;
                log.Append("Start server...");
                richTextBox1.Text= log.ToString();
            }

            while (true)
                try
                {
                    HttpListenerContext request = listener.GetContext();
                    ThreadPool.QueueUserWorkItem(ProcessRequest, request);
                }
                catch (HttpListenerException) { break; }
                catch (InvalidOperationException) { break; }
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
LEKAPb, 2014-09-29
@rgamretsky

Perhaps in your case you can do this:

// Тут запускаем прослушку 
Task.Factrory.StartNew(()=>{ 
 // Тут уже обрабатываем запросы
               while (true)
                try
                {
                    HttpListenerContext request = listener.GetContext();
                    ThreadPool.QueueUserWorkItem(ProcessRequest, request);
                }
                catch (HttpListenerException) { break; }
                catch (InvalidOperationException) { break; } });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question