BitmapPool.cs
2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AGVMapDemo.DemoModel
{
public class BitmapPool
{
private readonly ConcurrentBag<Bitmap> _bitmaps;
private readonly int _maxBitmaps;
private readonly int _bitmapWidth;
private readonly int _bitmapHeight;
public BitmapPool(int maxBitmaps, int bitmapWidth, int bitmapHeight)
{
_bitmaps = new ConcurrentBag<Bitmap>();
_maxBitmaps = maxBitmaps;
_bitmapWidth = bitmapWidth;
_bitmapHeight = bitmapHeight;
}
public Bitmap GetBitmap()
{
if (_bitmaps.TryTake(out Bitmap bitmap))
{
return bitmap;
}
else if (_bitmaps.Count < _maxBitmaps)
{
return new Bitmap(_bitmapWidth, _bitmapHeight);
}
else
{
// 可选:如果达到最大数量,可以选择抛出异常、等待、或其他处理策略
throw new InvalidOperationException("Bitmap pool is full and no available bitmaps.");
}
}
public void ReturnBitmap(Bitmap bitmap)
{
// 重置Bitmap为初始状态(如果需要)
// 例如:bitmap.SetPixel(0, 0, Color.Transparent); // 这只是一个示例,根据实际需求重置
bitmap.Dispose();
bitmap = null;
//GC.Collect();
// 将Bitmap返回到池中
if (_bitmaps.Count < _maxBitmaps)
{
_bitmaps.Add(bitmap);
}
// 可选:如果池已满,可以选择丢弃Bitmap、覆盖旧Bitmap、或进行其他处理
}
// 可选:提供一个方法来清理池中的所有Bitmap
public void ClearPool()
{
while (_bitmaps.TryTake(out Bitmap bitmap))
{
bitmap.Dispose();
}
}
}
}