本文整理汇总了C#中ObjectPool.GetObject方法的典型用法代码示例。如果您正苦于以下问题:C# ObjectPool.GetObject方法的具体用法?C# ObjectPool.GetObject怎么用?C# ObjectPool.GetObject使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ObjectPool
的用法示例。
在下文中一共展示了ObjectPool.GetObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestObjectPoolMethod
public void TestObjectPoolMethod()
{
int minCount = 1;
int max = 5;
// Creating a pool with minimum size of 5 and maximum size of 25, using custom Factory method to create and instance of ExpensiveResource
ObjectPool<ExpensiveResource> pool = new ObjectPool<ExpensiveResource>(minCount, max, () => new ExpensiveResource(/* resource specific initialization */));
Assert.IsTrue(pool.ObjectsInPoolCount == minCount);
using (ExpensiveResource resource = pool.GetObject())
{
// Using the resource
} // Exiting the using scope will return the object back to the pool
using (ExpensiveResource resource = pool.GetObject())
{
// Using the resource
} // Exiting the using scope will return the object back to the pool
using (ExpensiveResource resource = pool.GetObject())
{
// Using the resource
} // Exiting the using scope will return the object back to the pool
using (ExpensiveResource resource = pool.GetObject())
{
// Using the resource
} // Exiting the using scope will return the object back to the pool
using (ExpensiveResource resource = pool.GetObject())
{
// Using the resource
} // Exiting the using scope will return the object back to the pool
Assert.IsTrue(pool.ObjectsInPoolCount == 2);
// Creating a pool with wrapper object for managing external resources
ObjectPool<PooledObjectWrapper<ExternalExpensiveResource>> newPool = new ObjectPool<PooledObjectWrapper<ExternalExpensiveResource>>(() =>
new PooledObjectWrapper<ExternalExpensiveResource>(CreateNewResource())
{
WrapperReleaseResourcesAction = (r) => ExternalResourceReleaseResource(r),
WrapperResetStateAction = (r) => ExternalResourceResetState(r)
});
using (var wrapper = newPool.GetObject())
{
// wrapper.InternalResource.DoStuff()
}
using (var wrapper = newPool.GetObject())
{
// wrapper.InternalResource.DoStuff()
}
Assert.IsTrue(newPool.ObjectsInPoolCount == 6);
}
示例2: Main
private static void Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
Task task = new Task(() =>
{
if (Console.ReadKey().KeyChar == 'c' || Console.ReadKey().KeyChar == 'C')
{
cts.Cancel();
}
});
task.Start();
ObjectPool<MyClass> pool = new ObjectPool<MyClass>(() => new MyClass());
Parallel.For(0, 1000000, (i, loopstate) =>
{
MyClass mc = pool.GetObject();
Console.CursorLeft = 0;
Console.WriteLine("{0:####.####}", mc.GetValue(i));
pool.PutObject(mc);
if (cts.Token.IsCancellationRequested)
{
loopstate.Stop();
}
});
Console.WriteLine("Press the Enter key to exit.");
Console.ReadLine();
}
示例3: Main
/// <summary>
/// Example usages of ObjectPool.
/// </summary>
private static void Main()
{
// Creating a pool with minimum size of 5 and maximum size of 25, using custom Factory
// method to create and instance of ExpensiveResource.
var pool = new ObjectPool<ExpensiveResource>(5, 25, () => new ExpensiveResource(/* resource specific initialization */));
using (var resource = pool.GetObject())
{
// Using the resource...
resource.DoStuff();
} // Exiting the using scope will return the object back to the pool.
// Creating a pool with wrapper object for managing external resources, that is, classes
// which cannot inherit from PooledObject.
var newPool = new ObjectPool<PooledObjectWrapper<ExternalExpensiveResource>>(() =>
new PooledObjectWrapper<ExternalExpensiveResource>(CreateNewResource())
{
WrapperReleaseResourcesAction = r => ExternalResourceReleaseResource(r),
WrapperResetStateAction = r => ExternalResourceResetState(r)
});
using (var wrapper = newPool.GetObject())
{
// wrapper.InternalResource contains the object that you pooled.
wrapper.InternalResource.DoOtherStuff();
} // Exiting the using scope will return the object back to the pool.
}
示例4: TickAlgorithm
protected override Bitmap TickAlgorithm(Color?[,] current, Color?[,] next, ObjectPool<Bitmap> _pool, bool runParallel)
{
var bmp = _pool.GetObject();
using (FastBitmap fastBmp = new FastBitmap(bmp))
{
// For every row
Action<int> body = i =>
{
// For every column
for (int j = 0; j < _height; j++)
{
int count = 0;
int r = 0, g = 0, b = 0;
// Count neighbors
for (int x = i - 1; x <= i + 1; x++)
{
for (int y = j - 1; y <= j + 1; y++)
{
if ((x == i && j == y) || x < 0 || x >= _width || y < 0 || y >= _height) continue;
Color? c = current[x, y];
if (c.HasValue)
{
count++;
r += c.Value.R;
g += c.Value.G;
b += c.Value.B;
}
}
}
// Heuristic for alive or dead based on neighbor count and current state
if (count < 2 || count >= 7) next[i, j] = null;
else if (current[i, j].HasValue && (count == 2 || count == 5 || count == 7)) next[i, j] = current[i, j];
else if (!current[i, j].HasValue && (count == 2 || count == 7)) next[i, j] = Color.FromArgb(r / count, g / count, b / count);
else next[i, j] = null;
// Render the cell
fastBmp.SetColor(i, j, current[i, j] ?? Color.White);
}
};
// Process the rows serially or in parallel based on the RunParallel property setting
if (runParallel)
{
Parallel.For(0, _width,
body);
}
else
{
for (int i = 0; i < _width; i++)
body(i);
}
}
return bmp;
}
示例5: GetPut
public void GetPut()
{
var pool = new ObjectPool<DisposedTracking>(() => new DisposedTracking());
var item1 = pool.GetObject();
item1.Use();
var item2 = pool.GetObject();
item2.Use();
pool.PutObject(item2);
pool.PutObject(item1);
var item3 = pool.GetObject();
item3.Used.Should().BeTrue();
var item4 = pool.GetObject();
item4.Used.Should().BeTrue();
}
示例6: PutRecyclesObj
public void PutRecyclesObj()
{
var pool = new ObjectPool<DisposedTracking>(() => new DisposedTracking());
var item1 = pool.GetObject();
item1.Use();
pool.PutObject(item1);
item1.Disposed.Should().BeTrue();
}
示例7: CreatePool
public void CreatePool()
{
Type t = typeof(Entity);
_Pool = new ObjectPool();
_Pool.RegisterType(t, Create, 1, 10, 10);
var obj = _Pool.GetObject(t);
Assert.IsNotNull(obj);
Assert.AreEqual(t, obj.GetType());
_ObjectFromPool = obj as Entity;
}
示例8: ObjectPoolTest
public void ObjectPoolTest() {
var pool = new ObjectPool<int>(() => Rnd.Next(1, 99999));
Parallel.For(0, TestCount, i => pool.PutObject(Rnd.Next(1, 99999)));
Parallel.For(0, TestCount,
i => {
var item = pool.GetObject();
if(IsDebugEnabled)
log.Debug("item=" + item);
});
Assert.AreEqual(0, pool.Count);
}
示例9: Can_Create_Object_When_Not_Exists
public void Can_Create_Object_When_Not_Exists() {
var pool = new ObjectPool<int>(() => {
var result = Rnd.Next(1, 99999);
if(IsDebugEnabled)
log.Debug("Pool에 객체가 없어서 객체 생성 함수로부터 생성합니다. 생성 객체=" + result);
return result;
});
// Pool 에 넣지는 않고 꺼내기만 합니다.
//
Parallel.For(0, TestCount,
i => {
var item = pool.GetObject();
if(IsDebugEnabled)
log.Debug("Object Pool로부터 얻은 객체=" + item);
});
Assert.AreEqual(0, pool.Count);
}
示例10: Main
static void Main(string[] args)
{
Console.WriteLine("Is Server GC: " + GCSettings.IsServerGC);
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
Console.WriteLine("Compaction mode: " + GCSettings.LargeObjectHeapCompactionMode);
Console.WriteLine("Latency mode: " + GCSettings.LatencyMode);
GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
Console.WriteLine("New Latency mode: " + GCSettings.LatencyMode);
var pool = new ObjectPool<FakeItem>(() => new FakeItem(), 1000, true);
var watch = Stopwatch.StartNew();
const int Iterations = 10000000;
Action c = () =>
{
for (int i = 0; i < Iterations; i++)
{
var obj = pool.GetObject();
// Thread.SpinWait(rnd.Next(10) + 1);
Thread.SpinWait(4);
pool.PutObject(obj);
}
};
var t1 = Task.Factory.StartNew(c);
var t2 = Task.Factory.StartNew(c);
var t3 = Task.Factory.StartNew(c);
var t4 = Task.Factory.StartNew(c);
var t5 = Task.Factory.StartNew(c);
var t6 = Task.Factory.StartNew(c);
Task.WaitAll(t1, t2, t3, t4, t5, t6);
Console.WriteLine("Completed in " + watch.Elapsed.TotalMilliseconds + "ms");
}
示例11: Main
private static void Main(string[] args)
{
ObjectPool<MyClass> pool = new ObjectPool<MyClass>(() => new MyClass());
Stopwatch watchParallel = new Stopwatch();
watchParallel.Start();
Console.WriteLine("start......");
//Create a high demand for MyClass objects.
Parallel.For(0, 100, (i, loopState) =>
{
MyClass mc = pool.GetObject();
// This is the bottleneck in our application. All threads in this loop
// must serialize their access to the static Console class.
Console.WriteLine("pool 1 :{0:####.##} -> {1} Created: {2}; Added to pool: {3}", mc.GetValue(i), mc.GetValue(0), pool.CreatedObjectsCount, pool.AddedToPoolCount);
pool.PutObject(mc);
});
Console.WriteLine("stop......");
watchParallel.Stop();
Console.WriteLine("Created: {0}; Added to pool: {1}, removed: {2}", pool.CreatedObjectsCount, pool.AddedToPoolCount, pool.RemovedObjectsFromBagCount);
int count = GC.CollectionCount(0);
Console.WriteLine("Сборок мусора " + count + ", время выполнения: " + watchParallel.Elapsed);
Console.WriteLine("Press the Enter key to exit.");
Console.ReadLine();
GC.Collect();
{
Console.WriteLine("start......");
count = GC.CollectionCount(0) - 1;
Stopwatch watchOnlyThread = new Stopwatch();
watchOnlyThread.Start();
for (int i = 0; i < 1000; i++)
{
MyClass mc = pool.GetObject();
// This is the bottleneck in our application. All threads in this loop
// must serialize their access to the static Console class.
Console.WriteLine("pool 2 :{0:####.##} -> {0} -> {1} Created: {2}; Added to pool: {3}", mc.GetValue(i), mc.GetValue(0), pool.CreatedObjectsCount, pool.AddedToPoolCount);
pool.PutObject(mc);
}
watchOnlyThread.Stop();
count = GC.CollectionCount(0) - count;
Console.WriteLine("Сборок мусора " + count + ", время выполнения в одном потоке: " + watchOnlyThread.Elapsed);
Console.WriteLine("pool 1 : Created: {0}; Added to pool: {1}, removed: {2}", pool.CreatedObjectsCount, pool.AddedToPoolCount, pool.RemovedObjectsFromBagCount);
Console.ReadKey();
}
{
Console.ReadKey();
count = GC.CollectionCount(0) - 1;
Stopwatch watchOnlyThread = new Stopwatch();
watchOnlyThread.Start();
for (int i = 0; i < 100; i++)
{
MyClass mc = new MyClass();
// This is the bottleneck in our application. All threads in this loop
// must serialize their access to the static Console class.
Console.WriteLine("{0:####.##} -> {1}", mc.GetValue(i), mc.GetValue(0));
}
watchOnlyThread.Stop();
count = GC.CollectionCount(0) - count;
Console.WriteLine("Сборок мусора " + count + ", время выполнения в одном потоке: " + watchOnlyThread.Elapsed);
}
}
示例12: ShouldFillUntilMaximumSize
public void ShouldFillUntilMaximumSize(int maxSize)
{
var pool = new ObjectPool<MyPooledObject>(0, maxSize);
var objects = new List<MyPooledObject>();
for (var i = 0; i < maxSize * 2; ++i)
{
var obj = pool.GetObject();
objects.Add(obj);
}
foreach (var obj in objects)
{
(pool as IObjectPoolHandle).ReturnObjectToPool(obj, false);
}
Assert.AreEqual(maxSize, pool.ObjectsInPoolCount);
}
示例13: ShouldHandleClearAndThenReachMinimumSizeAtLaterUsage
public void ShouldHandleClearAndThenReachMinimumSizeAtLaterUsage()
{
var pool = new ObjectPool<MyPooledObject>();
using (var obj = pool.GetObject())
{
}
pool.Clear();
// Usage #A
using (var obj = pool.GetObject())
{
}
// Usages #B
using (var obj = pool.GetObject())
{
}
using (var obj = pool.GetObject())
{
}
using (var obj = pool.GetObject())
{
}
// Despite usage #B, count should always be fixed.
pool.ObjectsInPoolCount.ShouldBe(pool.MinimumPoolSize);
}
示例14: ShouldHandleClearAndThenPoolCanBeUsedAgain
public void ShouldHandleClearAndThenPoolCanBeUsedAgain()
{
var pool = new ObjectPool<MyPooledObject>();
using (var obj = pool.GetObject())
{
}
pool.Clear();
using (var obj = pool.GetObject())
{
}
pool.ObjectsInPoolCount.ShouldBe(pool.MinimumPoolSize);
}
示例15: ShouldHandleClearAfterSomeUsage
public void ShouldHandleClearAfterSomeUsage()
{
var pool = new ObjectPool<MyPooledObject>();
using (var obj = pool.GetObject())
{
}
pool.Clear();
pool.ObjectsInPoolCount.ShouldBe(pool.MinimumPoolSize);
}