初来乍到,送大家一个处理缓冲的设计
初来乍到,送大家一个处理缓冲的设计
大家都是高手,我就直接送代码好了。
该设计可以有很多变种,比如可以使用多种的Type。这个根据需要对结构进行调整即可。
public interface IBufferItem
{
bool Used{ get;set;}
}
/// <summary>
/// BufferStorage 的摘要说明。
/// </summary>
public class BufferStorage
{
private static readonly string m_InterfaceName = typeof( IBufferItem ).FullName;
private System.Collections.ArrayList ar = new System.Collections.ArrayList();
public BufferStorage(){}
/// <summary>
/// 获取没有被占用的缓冲,若没有空的缓冲则自动创建一个缓冲,
/// 不可以将缓冲的Buffer在外部使用,避免缓冲不被施放导致内存无限增加
/// </summary>
/// <returns></returns>
public IBufferItem GetUnusedBuffer( System.Type type )
{
if( type.GetInterface( m_InterfaceName ) == null )
return null;
System.Threading.Monitor.Enter( ar.SyncRoot );
try
{
foreach( IBufferItem bu in ar )
{
if( ( bu.Used == false ) && ( bu.GetType() == type ) )
{
bu.Used = true;
return bu;
}
}
IBufferItem rcb = System.Activator.CreateInstance( type ) as IBufferItem;
if( rcb == null )
return null;
rcb.Used = true;
ar.Add( rcb );
return rcb;
}
catch
{
return null;
}
finally
{
System.Threading.Monitor.Exit( ar.SyncRoot );
}
}
}
先说明一下为什么使用该设计。
某些情况下,我们需要一些临时的缓冲来处理事务。但这些缓冲往往在使用后就不需要使用,也就是说临时的空间。而在大量的申请内存空间时候,又需要消耗比较长的时间和资源,因此,设计这个结构,是利用已经申请过的资源,当然,如果缓冲比较小的话,还是直接申请比较好。
具体使用的方法为:
1。定义一个缓冲结构(类)。
2。在该结构(类)上实现IBufferItem接口。
3,使用时候,实现一个BufferStorage实例,通过该实例的方法GetUnusedBuffer来获取缓冲结构,其中的参数就是定义的缓冲结构(类)的类型。
4。在缓冲使用完毕后,需要对IBufferItem的Used属性赋值false,以释放该缓冲的占有。
例:
//实现缓冲类
public BytesBuffer : IBufferItem
{
private bool m_bUsed = false;
private byte[] m_Buffer = new byte[ 10240000]; //大空间缓冲
public bool Used
{
get{ return m_bUsed; }
set{ m_bUsed = value; }
}
public byte[] Buffer
{
get{ return m_Buffer; }
}
}
////使用
public class SomeClass
{
private static BufferStorage m_Storage = new BufferStorage();
private static System.Type m_BufferType = typeof( BytesBuffer );
public void SomeMethod()
{
//获取缓冲
BytesBuffer buf = m_Storage.GetUnusedBuffer( m_BufferType ) as BytesBuffer ;
if( buf == null )
.......
try
{
//使用缓冲
buf.Buffer
}
finally
{
//施放
buf.Used = false;
}
}
}
浙公网安备 33010602011771号