Implementation of the C # object pool (can limit the maximum number of instances, similar to the Maxinstancecount functionality of WCF)

Source: Internet
Author: User
Tags sleep thread throw exception

Object pooling services can reduce the overhead of creating each object from scratch. When an object is activated, it is extracted from the pool. When you deactivate an object, it is put back in the pool, waiting for the next request.

Let's take a look at how to deal with object pooling in the main thread:

static void Main (string[] args) {instancepoolresolver.register<orderqueryserviceinterface, Orderq
    
            Ueryservice> ();
                while (true) {Thread.Sleep (2000);
    
                Console.clear (); for (int i = 0; i < 20;i++) {ThreadPool.QueueUserWorkItem (new WaitCallback) (consum
                Eobject)); }} private static void Consumeobject (object state) {Orderqueryser
            Viceinterface srv = null; The try {using (SRV = instancepoolresolver.resolve<orderqueryserviceinterface> ())//is fetched from the object pool Object, there is no available object then throw exception {Console.WriteLine ("Object ID--->" + srv.
                    GetHashCode ());  Thread.Sleep (1000); Intentionally long time consuming object} catch (Exception ex) {Console.writeli NE (ex. MEssage); finally {if (SRV!= null) srv.
            Dispose (); }
        }

Operation Effect:

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.