C # Implementation of Object pool

Source: Internet
Author: User

The object pool service reduces the system overhead of creating each object from scratch. When an object is activated, it is extracted from the pool. When the object is disabled, it is put back into the pool and waits for the next request.
Let's take a look at how to deal with the object pool in the main thread:


Static void Main (string [] args)
{
InstancePoolResolver. Register <OrderQueryServiceInterface, OrderQueryService> ();

While (true)
{
Thread. Sleep (2000 );
Console. Clear ();

For (int I = 0; I <20; I ++)
{
ThreadPool. QueueUserWorkItem (new WaitCallback (ConsumeObject ));
}
}
}

Private static void ConsumeObject (object state)
{
OrderQueryServiceInterface srv = null;
Try
{
Using (srv = InstancePoolResolver. Resolve <OrderQueryServiceInterface> () // retrieves an object from the object pool. If no available object exists, throw exception
{
Console. WriteLine ("Object ID --->" + srv. GetHashCode ());
Thread. Sleep (1000); // deliberately occupies the object for a long time
}
}
Catch (Exception ex)
{
Console. WriteLine (ex. Message );
}
Finally
{
If (srv! = Null)
Srv. Dispose ();
}
} Running effect:

 

There are only two instances at most. Where can I set this quantity? See

 

Tag through Attribute.

Next let's take a look at the core InstancePoolResolver class


Public sealed class InstancePoolResolver
{
Private static Dictionary <Type, Type> typeMappers = new Dictionary <Type, Type> ();
Private static Dictionary <Type, int> typeMappersMaxInstanceCount = new Dictionary <Type, int> ();
Private static Dictionary <Type, List <PoolableObject> typeInstances = new Dictionary <Type, List <PoolableObject> ();

Private static object o4lock = new object ();
Public static void Register <T, TProvider> ()
Where TProvider: class, new ()
{
If (typeMappers. ContainsKey (typeof (T )))
Throw new Exception ("Key existed ");

Lock (o4lock)
{
Type t = typeof (T );
TypeMappers. Add (t, typeof (TProvider ));
TypeInstances. Add (t, new List <PoolableObject> ());

InstanceSettingAttribute setting = GetInstanceSettingAttribute (typeof (TProvider ));
TypeMappersMaxInstanceCount. Add (t, setting. MaxInstanceGlobal );
}
}

Public static T Resolve <T> ()
Where T: PoolableObject
{
Type t = typeof (T );
If (! TypeMappers. ContainsKey (t) |! TypeInstances. ContainsKey (t ))
Throw new Exception ("Key empty, register please ");

Lock (o4lock)
{
List <PoolableObject> instances = typeInstances [t];
If (instances = null)
{
Instances = new List <PoolableObject> ();
TypeInstances [t] = instances;
}
Foreach (PoolableObject o in instances) // check whether there are existing idle objects
{
If (o. IsInPool)
{
O. IsInPool = false;
Return (T) o;
}
}
If (instances. Count <typeMappersMaxInstanceCount [t]) // new object to the object pool
{
Type type = typeMappers [t];
PoolableObject obj = (PoolableObject) Activator. CreateInstance (type );
Instances. Add (obj );
Obj. IsInPool = false;
Return (T) obj;
}
}
Throw new Exception ("Object Pool fulled! "); // No redundant resources
}

Private static InstanceSettingAttribute GetInstanceSettingAttribute (Type type)
{
Object [] attrs = type. GetCustomAttributes (typeof (InstanceSettingAttribute), false );
If (attrs = null | attrs. Count () = 0)
Return new InstanceSettingAttribute () {MaxInstanceGlobal = 10 };

Return (InstanceSettingAttribute) attrs [0];
}
}

Related Article

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.