Application of improved synchronous waiting network server

Source: Internet
Author: User

Train of thought: ThreadPool static method RegisterWaitForSingleObject is specifically to solve this problem, it can wait for a wait handle, after the wait handle received a signal to execute a callback method, which solves the use of a separate thread to wait for the signal Problems, reducing the idle threads. In order to demonstrate this scenario, we use the HttpListener class to create a network server, a request to the client to call a method to process the request asynchronously, before the request is processed or timed out, will not return response to the client, the client's request has been waiting here. ThreadPool.RegisterWaitForSingleObject registers the wait handle returned by the asynchronous method call, which sends a signal to the wait handle when the asynchronous method executes, executing the callback, and if the wait handle does not receive a signal within the specified time, We return a 504 timeout response to the client or return the processing result to the client.

Of course ThreadPool.RegisterWaitForSingleObject can also register a global wait handle instead of the wait handle returned by an asynchronous method call, which can be more flexible, send a request to a backend service, and wait for a global handle for a period of time, etc. Receives the corresponding response of the backend service and sends a signal to the global wait handle, which returns the processing result to the client.

In addition, because the WaitOrTimerCallback delegate does not accept the object argument passed by reference, we use a global dictionary (_dicthandlerresults) to hold the result information for each request processing, and to obtain a sequence number upon receipt of the request. Also tells the asynchronous request processing method (Asynchandlerrequest) and the wait handle callback method (Requestcompletecallback) registered by the thread pool. The request processing method takes the processing result into the global request processing result dictionary after processing the request with the incoming serial number as key, and the thread pool wait handle callback method also takes the request processing result in the global dictionary according to this serial number. Considering that the queued request may not be infinite, so the global dictionary has the upper limit, tentatively 100,000, and then the serial number is from 1w to 10w, so that the global dictionary can be used without any lock, and almost no occurrence through a serial number to get the request processing results and this request does not match, Unless the requested queue is greater than 100,000.

The implementation code for the service side is as follows:

 using System;


using System.Collections.Generic;


using System.IO;


using System.Net;


using System.Runtime.Remoting.Messaging;


using System.Text;


using System.Threading;


namespace Server


{


Internal class Program


{


private static void Main (string[] args)


{


Try


{


myhttpserver myhttpserver = new Myhttpserver ();


Myhttpserver.start ();


Console.readkey ();


Myhttpserver.stop ();


}


catch (Exception ex)


{


Console.WriteLine (ex);


Console.readkey ();


}


}


}


Internal class Myhttpserver


{


Private Const string prefixes = "http://+:8080/service/";


Private Const int max_pending_request = 100000;


private static int _currentseq = 0;


private static readonly Random _random = new Random ();


private static readonly dictionary<int, string> _dicthandlerresults = new Dictionary<int, STRING&G T (max_pending_request);


private readonly HttpListener _listener;


public myhttpserver ()


{


if (! httplistener.issupported)


throw new NotSupportedException ("system does not support HttpListener");


_listener = new HttpListener ();


for (int i = 0; i < max_pending_request; i++)


{


_dicthandlerresults.add (i,string. Empty);


}


}


public void Start ()


{


_listener. Prefixes.add (prefixes);


_listener. Start ();


Console.WriteLine ("Listening");


_listener. Begingetcontext (Listenercallback, _listener);


}


public void Stop ()


{


_listener. Stop ();


}


private static int getseq ()


{


if (++_currentseq = = max_pending_request)


_currentseq = 0;


return _currentseq;


}


private static void Showthreadcount ()


{


int workerthreads, iothreads, maxWorkerThreads, Maxiothreads;


Threadpool.getmaxthreads (out of maxWorkerThreads, out maxiothreads);


Threadpool.getavailablethreads (out of workerthreads, out iothreads);


Console.WriteLine ("WorkerThreads: {0},iothreads:{1}", Maxworkerthreads-workerthreads, Maxiothreads-i Othreads);


}


private static void Listenercallback (IAsyncResult result)


{


Try


{


HttpListener listener = (HttpListener) result. asyncstate;


Listener. Begingetcontext (listenercallback, listener);


Showthreadcount ();


httplistenercontext context = listener. Endgetcontext (result);


HttpListenerRequest request = context. Request;


httplistenerresponse response = context. Response;


int tempkey = GETSEQ ();


Console.WriteLine ("Current seq: {0}", Tempkey);


//Here mimics asynchronous IO-intensive operations, which do not have to be invoked asynchronously if they are computationally intensive


//Because here itself is thread pool threads in processing, you can do some asynchronous remoting calls, socket calls, and so on.


//or after sending a request to the back-end service, wait for the answer to find a matching Waithandler call its set method.


asynchandlerrequestdelegate d = asynchandlerrequest;


IAsyncResult ar = d.begininvoke (Request, Tempkey, asynchandlerrequestcallback, NULL);


ThreadPool.


RegisterWaitForSingleObject (


ar. AsyncWaitHandle,


Requestcompletecallback,


New object[] {response, tempkey},


5000, true);


}


catch (Exception ex) {Console.WriteLine (ex);}


}


Private delegate void Asynchandlerrequestdelegate (httplistenerrequest request, int key);


private static void Asynchandlerrequest (HttpListenerRequest request, int key)


{


int rnd = _random. Next (1, 8);


Thread.Sleep (RND * 1000); Here imitate the complex processing, the real system kills you and you do not have the thread pool line Chengri sleep Oh


_dicthandlerresults[key] = string. Format ("This request handler by {0} miniut.", Rnd);


}


private static void Asynchandlerrequestcallback (IAsyncResult ar)


{


Asynchandlerrequestdelegate d = (asynchandlerrequestdelegate) ((asyncresult) AR). AsyncDelegate;


D.endinvoke (AR);


}


private static void Requestcompletecallback (object state, bool istimeout)


{


object[] states = (object[]) state;


httplistenerresponse response = (httplistenerresponse) states[0];


int key = (int) states[1];


Stream output = null;


Try


{


output = response. OutputStream;


string Requesthandlerresult;


if (istimeout)


Requesthandlerresult = "504 Time Out";


Else


_dicthandlerresults.trygetvalue (key, out requesthandlerresult);


byte[] buffer = Encoding.UTF8.GetBytes (Requesthandlerresult);


Response. ContentLength64 = buffer. Length;


output. Write (buffer, 0, buffer.) Length);


}


catch (Exception ex)


{


Console.WriteLine (ex);


}


finally


{


try {if (output!= null) output. Close (); }catch {}


}


}


}


}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.