Implement. NET coprocessor from scratch (i)

Source: Internet
Author: User

The concept of the process, as far as I am concerned, comes from learning to go, it can be summed up in a sentence, "single-threaded non-blocking asynchronous processing," that is, first of all, its scope is for a single thread, a thread can run multiple code snippets, when running to encounter IO waits (including network io, disk IO, etc., When common database operations, Web service calls are both IO waits), automatically switches to execution on other code fragments, and then goes back to the code fragment that has completed IO waits before executing or encountering the IO wait again, so that the thread is not blocked, and multiple fragments can be gradually processed (provided that there is IO waiting in the code, otherwise or sequential processing), the above is the definition of the association, from the description can be seen, this processing is particularly suitable for high-io, low CPU computing programs, in reality, most of the Web application is this model, That's why the language of Go is getting more and more nodejs now.

The following figure depicts the operation of the co-process

The actual processing order of the process (the actual and the co-scheduling program)

In. NET, the Web Processing (ASP) mode is multithreaded asynchronous, in fact, is also very good, can also do no blocking, make full use of CPU resources, here does not talk about this mode, only talk about the process mode.

So how does the. NET implement the co-process? The first thing to do here is to introduce a keyword, and the yield,.net process is to use it to achieve

Yield is used to process iterators (IEnumerator), using the characteristics of iterators to indirectly provide a way to interrupt the recovery process, speaking in code

1     class Program2     {3         Static voidMain (string[] args)4         {5             varresult=Testyield ();6 7 result. MoveNext ();8 Console.WriteLine (Result. current);9 Ten result. MoveNext (); One Console.WriteLine (Result. current); A  - result. MoveNext (); - Console.WriteLine (Result. current); the  - result. MoveNext (); -  - Console.read (); +  -         } +  A  at         Staticienumerator<string>Testyield () -         { -             yield return "A"; -Console.WriteLine ("execution complete a"); -             yield return "B"; -Console.WriteLine ("execution Complete B"); in             yield return "C"; -Console.WriteLine ("execution Complete C"); to         } +}

Execution results are

As can be seen from the code above, whenever the MoveNext method is used, the code proceeds from the yield return statement, and when it encounters a yield return or method completion, returns the caller again, the iterator pattern (which is itself one of 23 design patterns), Provides the ability to execute code in segments, which we can use to complete the process, there is a particular need to note that when we call the Testyield method, you will find that it is not actually executed until the first time we call the MoveNext method, This method is really starting to be executed, remember LINQ, LINQ says, only a method such as ToList (), Count () is called, does it really start to compute, and does this look like it? In fact, inside LINQ, Iterators are used.

Well, now that you have the basic elements of the implementation of the process, you can start to build, the two-part, the coprocessor and the coprocessor, the coprocessor is responsible for scheduling and execution, the co-process unit is used to handle the actual business, the co-process container provides a register method to register each process unit, Keep talking in code.

1     /// <summary>2     ///co-process container interface3     /// </summary>4      Public InterfaceIcoroutinecontainer5     {6         /// <summary>7         ///registering a co-process unit8         /// </summary>9         /// <param name= "unit" >co-process Unit</param>Ten         voidRegister (icoroutineunit unit); One         /// <summary> A         ///Execution -         /// </summary> -         voidRun (); the } -     /// <summary> -     ///co-process Unit interface -     /// </summary> +      Public InterfaceIcoroutineunit -     { +         /// <summary> A         ///Processing Business at         /// </summary> -         /// <returns></returns> -Ienumerator<task>Do (); -}

These two interfaces are the core interface of the whole implementation, the following basic implementation of the process container

<summary>///The basic implementation of the co-process container///</summary> public class Coroutinecontainerbase:icoroutinecontainer {///<summary>///Storage of the list of co-units//</summary> private list<unititem> _unit        s = new list<unititem> (); <summary>////Storage of newly registered co-units, separated from the list of co-process units, implementation of registration and implementation of non-impact///</summary> private List<unitite        m> _addunits = new list<unititem> (); <summary>///error handling///</summary> private action<icoroutineunit, exception> _er        Rorhandle; <summary>///constructor function///</summary>//<param name= "Errorhandle" > Error handling </param&        Gt Public Coroutinecontainerbase (Action<icoroutineunit, exception> errorhandle) {_errorhandle = Erro        Rhandle; } public void Register (Icoroutineunit unit) {Lock (_addunits) {_addun Its. ADD (nEW Unititem () {unit = unit, Unitresult = null}); }} public void Run () {//Open a separate task execution task.run () = {// Loop processing the coprocessor unit while (true) {//Adds the newly registered Coprocessor unit to the list lock (_addun                            Its) {foreach (var addItem in _addunits) { _units.                        ADD (AddItem);                    } _addunits.clear ();                        }//Process the co-unit foreach (var item in _units) { if (item. Unitresult = = null) {var result = Item.                            Unit.do (); Run to the next breakpoint try {result.                            MoveNext (); } catch (ExceptIon ex) {_errorhandle (item.                                Unit, ex); _units.                                Remove (item);                            Break } item.                        Unitresult = result;                            } else {//check whether the wait has been completed and continue running if it is completed if (item. UnitResult.Current.IsCanceled | | Item. UnitResult.Current.IsCompleted | | Item.                                UnitResult.Current.IsFaulted) {var nextresult = true; try {NextResult = Item.                                Unitresult.movenext ();                                    } catch (Exception ex) { _errorhandle (item.                                    Unit, ex); _units. Remove (Item);                                Break } if (!nextresult) {_uni Ts.                                    Remove (item);                                Break            }                            }                        }                    }                                    }        });            }///<summary>//////</summary> private class Unititem { <summary>///////</summary> public icoroutineunit unit {get; Set }///<summary>///The iterator used by the////</summary> public IENUMERATOR&L T        Task> Unitresult {get; set;} }    }

Implement two co-process units

<summary>///co-process Unit 1//execute a network IO, visit 163 site///</summary> public class Action1:icoroutineunit            {public ienumerator<task> do () {Console.WriteLine ("Start Execution Action1");            HttpClient client = new HttpClient ();            Yield return Innerdo ();        Console.WriteLine ("End Execution Action1");            } private Task Innerdo () {HttpClient client = new HttpClient (); Return client.        Getasync ("http://www.163.com"); }}////<summary>///2///To perform a network IO, visit 163 site///</summary> public class Action2:icoro            Utineunit {public ienumerator<task> do () {Console.WriteLine ("Start Execution Action2");            Yield return Innerdo ();        Console.WriteLine ("End Execution Action2");            } private Task Innerdo () {HttpClient client = new HttpClient (); Return client.        Getasync ("http://www.163.com"); }}

Main program Call execution

        Static voidMain (string[] args) {            //error handling is simply displaying the error in the consoleaction<icoroutineunit,exception> errorhandle = (unit, ex) = ={Console.WriteLine (ex.              ToString ());            }; //initializing the co-process containerIcoroutinecontainer coroutinecontainerbase =Newcoroutinecontainerbase (Errorhandle); //Register Action1Coroutinecontainerbase.register (NewAction1 ()); //Register Action2Coroutinecontainerbase.register (NewAction2 ()); //Running the containerCoroutinecontainerbase.run ();        Console.read (); }

Execution results

Note that the order of each execution may be different, depending on the network speed, but you can clearly see the fragment execution of the code.

At this point, one of the most basic process frameworks has been completed

To implement. NET coprocessor from scratch (i)

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.