Click here to Skip to main content
15,896,539 members
Articles / Programming Languages / C#

C# Object Pooling

Rate me:
Please Sign up or sign in to vote.
3.67/5 (9 votes)
12 Oct 20073 min read 72.1K   512   35  
A simple article on object pooling for the brave
using System;
using System.Collections.Generic;
using System.Text;
namespace ObjectPool {
	public class SampleObject : IObjectPoolMethods {

		public event EventHandler Disposing;
		private byte[] vectorArray = new byte[1024 * 100];
		private bool mIsDisposed = false;
		private static Int64 mDisposeCount = 0;
		private static Int64 mObjectCount = 0;


		public static Int64 GetDisposeCount() {
			return mDisposeCount;
		}
		public static Int64 GetObjectCount() {
			return mObjectCount;
		}
		public static SampleObject New() {
			return ObjectPool<SampleObject>.GetInstance().GetObjectFromPool(null);
		}
		public bool IsDisposed() {
			return mIsDisposed;
		}


		/**
		 * <summary>
		 * This method is provide to perform 
		 * some work so it looks like the object was used
		 * for something important
		 * </summary>
		 */
		public void DoSomeWork() {
			unchecked {
				int total = 0;
				for (int i = 0; i < vectorArray.Length; i++) {
					total += vectorArray[i];
				}
				double average = total / vectorArray.Length;
			}
		}//end DoSomeWork



		private void Dispose(bool disposing) {
			if (disposing) {
				if (Disposing != null) {
					Disposing(this, new EventArgs());
				}
				mDisposeCount++;
				mIsDisposed = true;
				GC.SuppressFinalize(this);
			}
		}

		public void Dispose() {
			Dispose(true);
		}

		~SampleObject() {
			Dispose(false);
		}

		public void SetupObject(params object[] setupParameters) {
			System.Array.Clear(vectorArray, 0, vectorArray.Length);
			mIsDisposed = false;
		}


		public SampleObject() {
			mObjectCount++;
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect ERL GLOBAL, INC
United States United States
My company is ERL GLOBAL, INC. I develop Custom Programming solutions for business of all sizes. I also do Android Programming as I find it a refreshing break from the MS.

Comments and Discussions