More than a year has not used multi-threading. Recently I need to do an asynchronous e-mail, in order to write an example to colleagues, think of the previous written crawler,
A man who took me gave me a generic template class, and I thought the example was good, so I wrote the following code according to my own understanding.
The first is a general-purpose counter. Includes the current number of threads currently running, the number of successful executions success, the number of failed error executions, and the total number of completed finishes.
To make it easy for everyone to understand, I'd like to give you a brief explanation. The general process is this: first there are a number of tasks come in, you need to use these tasks multi-threaded to deal with. (I'm using a thread pool here.)
On the concept of pool we should be unfamiliar with the port. For example, the database connection pool.
Tasks are assigned one by one, and each task is to open a single child thread and perform tasks on one side while assigning tasks. There is a situation where there is no constant assignment of tasks,
Is that the task has been assigned a lot of, but not fast enough, this time need to wait for the main thread, and then assign a new task.
I use the above description in a daily life example to explain: a small hotel only 10 seats, 10 o'clock open, to 12 o ' Dinner time, outside the 100 guests,
Go into the restaurant and eat each other.
The first person enters, occupies 1 positions,
A second person enters, occupies 1 positions,
A third person enters, occupies 1 positions,
The fourth person entered the occupied position of 1,
The fifth person enters occupies the position 1, then the first person packs the walk, has a position to be empty,
Now we have used 4 positions, and as for what to sit in after coming in, this is out of control.
The sixth person entered the position of 1,... The nineth person came in, occupies 1 positions, 2nd person ate, tenth person came in, the first is a person came in, 12th came in,
The third man had finished, and the 13th man came in,
14th person want to come in, sorry, already full, to wait, after 1 minutes to see if there is no location, if no one left, the outside people have been unable to come in,
After five minutes, and then see a table four people have left, so the 14th person came in, the 15th person came in .... The following is similar to the previous ...
Nonsense, the code.
1. Classes that read and write to the previous counter first
Public Sealed classThreadcounter {Private intCurrent =0; Private intError =0; Private intSuccess =0; Private intfinish =0; Private Static ObjectWriteobj =New Object(); Public intGetCurrent () {intres =0; Lock(writeobj) {res=Current ; } returnRes; } Public intGetError () {intres =0; Lock(writeobj) {res=error; } returnRes; } Public intgetsuccess () {intres =0; Lock(writeobj) {res=success; } returnRes; } Public intGetfinish () {intres =0; Lock(writeobj) {res=finish; } returnRes; } Public voidsetaddcurrent () {Lock(writeobj) { current++; } } Public voidsetsuccess () {Lock(writeobj) {Success++; Current--; } } Public voidSetError () {Lock(writeobj) {error++; Current--; } } Public voidSetfinish () {Lock(writeobj) {Finish++; } } }
View Code
2. Subject run Business Processing class
Public classRunmanager { PublicRunmanager () {} Public intThreadCount {Get;Set; } Private Static intMaxthreadcount =Ten; /// <summary> ///Maximum number of open threads/// </summary> /// <param name= "ThreadCount" ></param> Public voidRunstart (intThreadmaxcount) { //Maximum number of open threadsConsole.WriteLine ("set maximum number of threads:"+threadmaxcount); Maxthreadcount=Threadmaxcount; RunTask ( -); } Public voidRunTask (intTaskcount) { stringMSS =""; string[] arr =New string[] {"|","/","-","\\" }; intj =0; while(true) {J++; if(j==4) {J=0; } console.clear (); Console.setcursorposition (1,0); Console.WriteLine ("Current Operating conditions"); Console.Write ("["+arr[j]+"]\t"); MSS=string. Format ("query:{0}, Current:{1}, success:{2}, Error:{3}, finish:{4}", Taskcount, Tc.getcurrent (), tc.getsuccess (), Tc.geterror (), Tc.getfinish ()); Console.WriteLine (MSS); Thread.Sleep ( -); if(taskcount>0&&tc.getcurrent () <Maxthreadcount) {Taskcount--; Tc.setaddcurrent (); Threadpool.unsafequeueuserworkitem (Ruancallback,0); } Else if(taskcount==0) {Taskcount= Random. Next ( -, the); } Else if(Tc.getcurrent () >=Maxthreadcount) {Thread.Sleep (6000); }}} threadcounter TC=NewThreadcounter (); Random Random=NewRandom (); Public voidRuancallback (Objectparms) { //will pass over the parameters, organized into the data to be queried, as well as processing data, writing files, packaging zip,//Send mail to notify users to download Try { intt = random. Next (3,7); Thread.Sleep (t* +); Tc.setsuccess (); } Catch(Exception) {tc.seterror (); } finally{tc.setfinish (); } //Console.WriteLine ("Current line program number:" + parms. ToString () + "\ t thread pause time:" + t); } }
View Code
3. Call
Static void Main (string[] args) { new Runmanager (); R.runstart (a); Console.read (); Console.WriteLine (" run end "); }
Let's take a look at the running effect
nice!
Original code Download: download
Multi-thread thread pool task management generic template