Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
ObjectPool
//Rextester.Program.Main is the entry point for your code. Don't change it. //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { class PoolResource : IDisposable { public void Dispose() { Console.WriteLine("Pool Resource Dispose Method called"); } } class ObjectPool<T>:IDisposable where T:IDisposable,new() { private class CacheEntry<U> : IDisposable where U:IDisposable { public bool InUse{get; set;} public U Resource{get; private set;} public CacheEntry(U resource) { InUse = false; Resource = resource; } public void Dispose() { if(Resource!=null) { Resource.Dispose(); } } } private List<CacheEntry<T>> _entries = new List<CacheEntry<T>>(); private int _capacity; public ObjectPool(int capacity) { _capacity = capacity; } public T AcquireResource() { foreach(var entry in _entries) { if(!entry.InUse) { entry.InUse = true; return entry.Resource; } } if(_entries.Count < _capacity) { var resource = new T(); var cacheEntry = new CacheEntry<T>(resource); cacheEntry.InUse = true; _entries.Add(cacheEntry); return resource; } throw new InvalidOperationException(); } public void ReleaseResource(T resource) { bool found = false; foreach(var entry in _entries) { if(entry.Resource.GetHashCode() == resource.GetHashCode()) { entry.InUse = false; found = true; break; } } if(!found) { throw new InvalidOperationException(); } } public void Dispose() { Console.WriteLine("Object Pool Dispose called!"); foreach(var d in _entries) { if(d != null) { d.Dispose(); } } } } public class Program { public static void Main(string[] args) { var objectPool = new ObjectPool<PoolResource>(2); using(objectPool) { var first = objectPool.AcquireResource(); Console.WriteLine(first.GetHashCode()); var second = objectPool.AcquireResource(); Console.WriteLine(second.GetHashCode()); try { var third = objectPool.AcquireResource(); Console.WriteLine(third.GetHashCode()); } catch(Exception ex) { Console.WriteLine(ex.ToString()); } objectPool.ReleaseResource(second); try { var fourth = objectPool.AcquireResource(); Console.WriteLine(fourth.GetHashCode()); } catch(Exception ex) { Console.WriteLine(ex.ToString()); } } } } }
run
|
edit
|
history
|
help
0
Knapsack Problem - recursive
CommandForce
Game v1.0.1
hello...
singly linked list traversal
30272 Program Ex4 if
Cont monad in C#
Problem: rstring
Shorten SMS Text
Found many section of times intersect.