Asp.net parallel and Multithreading

Source: Internet
Author: User

Asp tutorial. net parallel and Multithreading

The number of concurrent requests in the asp.net tutorial has many conditions, regardless of the program execution time and whether the program is blocked, it will be limited by the number of tcp connections on the server (generally, windows servers do not seem to have any restrictions, number of iis connections, which is limited by the clr thread pool.

Server tcp restrictions: [hklmsystemcurrentcontrolsetservicestcpipparameters] "enableconnectionratelimiting" = dword: 00000000. Change the value of this registry entry to "0". If it is a Windows server, this restriction is generally absent, for example, I do not have a 2003 error.

Iis connection limit: iis6 and below, and metabase under % systemroot % system32inetsrv. direct modification in xml files. For example, to modify the default asprequestqueuemax = "3000", you can set a larger queue for requests. Modify the default aspprocessorthreadmax = "25 ", set the concurrent request thread to a greater value. For details, refer to the relevant materials. Too many processes will take time to set the cpu switching thread. According to the online statement, the larger the number, the better, however, it can be set based on the concurrency and system performance. The iis7 configuration is different, and % systemroot % system32inetsrvconfigapplicationhost. in the config file, modify <serverruntime appconcurrentrequestlimit = "5000"/> and limit the number of concurrent requests,

Iis manager> applicationpools> advanced settings, queue length: 1000 modify the queue length. hklmsystemcurrentcontrolsetserviceshttpparameters maxconnections can be modified more.

. Net Framework restrictions

I think that after an asp.net program runs, it does not care about different iis versions. They have different lifecycles and iis6 has different processes, however, I think the process should be managed by at least three thread pools. One clr is responsible for the working thread pool of different request requests and one io processing thread, there is also an unmanaged thread pool for the process. The initialization and maximum number of thread pools hosted can be configured and set by the program, the unmanaged thread pool is used to send requests to clr for processing. When there are io or other asynchronous operations, it processes unmanaged threads. Of course, we can control the managed thread pool.. net version, which is different from the number of system CPUs and the number of initialization thread pools. For example, I currently use a single-cpu dual-core system, in. run the following code in the next mvc request of net4:

Int workthread = 0;
Int iothread = 0;
Threadpool. getmaxthreads (out workthread, out iothread );

The maximum worker thread pool and I/O thread pool obtained are both 200. However, based on relevant information, this value is 100 x number of CPUs (multiple CPUs in dual-core mode ), the value obtained in the windows program is larger, indicating that the number of threads given by the default system is different.

In different. in the. net version, machine. <processmodel autoconfig = "true"/> in config uses the default configuration.. net in different versions, the default number of threads and other information are directly written. You can modify the machine by modifying it. some values of the node in config for different purposes. The following parameters are configured by default:

Set maxworkerthreaders and maxiothreads to 100
Set maxconnection to 12 * Number of CPUs
Set minfreethreads to 88 * cpu usage
Set minworkerthreads to 50
 

Maximum number of threads = (maximum worker threads * Number of CPUs)-minimum number of Idle threads. Of course, there are other important parameters.

These are all changes to the configuration files in iis6 and iis7 classic modes. The ii7 integration mode is a little different. The maximum number of requests is determined by the following: maxconcurrentrequestspercpu: Limit the number of requests executed by each cpu, even if more threads are available. In. net 3.5 and earlier versions, the default value is 12, and in. net 4 is 5000. If it is set to 0, there is no limit; maxconcurrentthreadspercpu: Limit the number of threads that each cpu can process requests. The default value is 0. This is basically equivalent to no limit on the number of requests, and the <processmodel

Requestqueuelimit = "10000"/> added

Indicates that the request queuing queue is 10000, Which is set in % systemroot % system32inetsrvconfigapplicationhost. config. <serverruntime appconcurrentrequestlimit = "10000"/> adds the limit for parallel requests.

Look at a multi-threaded operation code using socket

The first two namespaces must be included:

Using system.net;

Using system.net. sockets;

Several frequently-used classes: (these items are detailed after you check msdn)

Iphostentry, dns, ipaddress, ipendpoint, and the most important socket

Ipendpoint: This is the network endpoint. It is a fixed address on the Network: a combination of an ip address and a port.

Next I will use a simple chat program I wrote as an example (short code)

Form1.cs

// Note that this is an integration of server and client.

Using system;
Using system. collections. generic;
Using system. componentmodel;
Using system. data;
Using system. drawing;
Using system. text;
Using system. windows. forms;
Using system.net;
Using system.net. sockets; // This is required to use socket.
Using system. io;
Using system. threading; // This is required for multithreading.

Namespace onlysocket
{
Public partial class form1: form // partial indicates that this code is only part of the form1 class. The form1 class inherits from the form class.
{
Public form1 ()
{
Initializecomponent (); // constructor to initialize the container.
}
Socket sock; // defines the object of a socket class (protected by default)
Thread th; // defines the object of a thread class
//

Public static ipaddress getserverip () // static function, which can be called without instantiation.
{
Iphostentry ieh = dns. gethostbyname (dns. gethostname (); // no more static functions of the dns class

// Or use dns. resolve () instead of gethostname ()
Return ieh. addresslist [0]; // return an instance of the address class. It is not surprising that addresslist is an array. A server may have n ip addresses.
}

Private void beginlisten () // socket listener function, which is used as a parameter to create a new thread.
{
Ipaddress serverip = getserverip (); // call the static function getserverip to obtain the local ipaddress.
Ipendpoint iep = new ipendpoint (serverip, convert. toint32 (tbport. text); // local endpoint
Sock = new socket (addressfamily. internetwork, sockettype. stream, protocoltype. tcp); // instantiate the sock Member
Byte [] bytemessage = new byte [100]; // The byte array buffer for storing messages. Note that the array representation method is different from that of c.
This. lbiep. text = iep. tostring ();
Sock. bind (iep); // an important function of the socket class, bound to an ip address,
While (true) // here, an endless loop is set to listen to the port. Some people will ask the endless loop, so the program will not get stuck. Note that this is only a class, there is no main function yet.
{
Try
{
Sock. listen (5); // OK, the sock can start listening after it is bound to a local endpoint. 5 indicates that the maximum number of connections is 5.
Socket newsock = sock. accept (); // an important method of the socket class: accept, which accepts socket connection requests from outside and returns a socket, this socket starts to process the conversation between this client and the server.
Newsock. receive (bytemessage); // Save the data sent by the client to the buffer zone.
String msg = "from [" + newsock. remoteendpoint. tostring () + "]:" + system. text. encoding. utf8.getstring (bytemessage) + "n"; // The getstring () function converts the byte array to the string type.
Rtbtalk. appendtext (msg + "n"); // display it in the text Control
}
Catch (socketexception se) // catch an exception,
{
Lbstate. text = se. tostring (); // display it. You can also customize the error here.
}
}
}

Private void btconnect_click (object sender, eventargs e) // event triggered by the connection button: connect to the server
{
Btconnect. enabled = false;
Btstopconnect. enabled = true;
Try
{
Th = new thread (new threadstart (beginlisten); // create a new thread for processing listening. This statement can be written separately, for example: threadstart ts = new threadstart (beginlisten); th = new thread (ts); however, note that the parameters of the threadstart constructor must be functions without parameters. the function name here is actually its pointer. Is it a delegate here?
Th. start (); // start the thread
Lbstate. text = "listenning ...";
}
Catch (socketexception se) // handle exceptions
{
Messagebox. show (se. message, "problem occurred", messageboxbuttons. OK, messageboxicon. information );
}
Catch (argumentnullexception AE) // an exception occurs when the parameter is null.
{
Lbstate. text = "parameter error ";
Messagebox. show (AE. message, "error", messageboxbuttons. OK, messageboxicon. warning );
}

}

Private void btstopconnect_click (object sender, eventargs e) // stop the listener
{
Btstopconnect. enabled = false;
Btconnect. enabled = true;
Sock. close (); // close the socket
Th. abort (); // terminate the listening thread

Lbstate. text = "listenning stopped ";
}

Private void btexit_click (object sender, eventargs e)
{
Sock. close ();
Th. abort ();
Dispose (); // clear the resource, that is, release the memory.
This. close (); // close the dialog box and exit the program.
}

Private void btsend_click (object sender, eventargs e)
{
Try
{
Ipaddress clientip = ipaddress. parse (tbtargetip. text); // static function parse () of ipaddress class: converts text to an instance of ipaddress.
Int clientport = convert. toint32 (tbport. text); // These conversion functions of c # are very convenient, not as troublesome as c ++.
Ipendpoint clientiep = new ipendpoint (clientip, clientport); // It is not very good to use client here ....,
Byte [] byte_message;
Socket = new socket (addressfamily. internetwork, sockettype. stream, protocoltype. tcp); there are many parameters during instantiation. This is tcp. the sockettype of tcp is stream: Data stream. If the protocol type is udp, It is data packet transmission, and qq is udp.
Socket. connect (clientiep); // another function of socket connect (ipendpoint). connect to a remote socket
Byte_message = system. text. encoding. utf8.getbytes (rtbwords. text); // It is used if utf8 supports Chinese characters.
Socket. send (byte_message );
Rtbtalk. appendtext ("n" + "my words:" + rtbwords. text + "n ");
Socket. shutdown (socketshutdown. both );
Socket. close ();
}
Catch (argumentnullexception AE)
{
Messagebox. show (AE. message, "parameter is blank", messageboxbuttons. okcancel, messageboxicon. information );
}
Catch (socketexception se)
{
Messagebox. show (se. message, "problem occurred", messageboxbuttons. OK, messageboxicon. information );
}
}

}
}

Program. cs

Using system;
Using system. collections. generic;
Using system. windows. forms;

Namespace onlysocket
{
Static class program
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[Stathread]
Static void main () // here is the main function.

{
Application. enablevisualstyles ();
Application. setcompatibletextrenderingdefault (false );
Application. run (new form1 ());
}
}
}


 

I have been writing for a long time, and I am tired enough. Although it is basic, I also reviewed it when I wrote it myself.

In fact, I am not very familiar with multithreading myself. I remember I wrote a multi-threaded scanner last summer. I don't know why. It would be very depressing to have a thread open above 50. in fact, at that time, I implemented it using new thread = thread (new threadstart (fun), and the method was very clumsy.

The code is like this:

First write a scan class:

Public class scan

{

Try {public scan () {... init ...}

Public void scan {... task cyclic scan...} // ip address and port in the task struct, and whether flag has been scanned}

Catch {}

}

Then the main function can do this:

Scan [] scan = new scan [xx]

Thread [] thread = new thread [xx];
For (int I = 0; I <xx; I ++)
{
Topology [I] = new scan (this, I );
Thread [I] = new thread (new threadstart (threads [I]. startscan ));
Thread [I]. start ();

}

In this way, you can simply implement multiple threads.

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.