SpStreamCache.cs 1.1 KB
Newer Older
timchen1002's avatar
update  
timchen1002 已提交
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
using System;
using System.Collections.Generic;

class SpStreamCache
{
    const int kSpStreamCacheMax = 10;
    static int sSpStreamCacheFreeIdx = -1;
    static SpStream[] sSpStreamCache = new SpStream[kSpStreamCacheMax];
    static readonly object sSpStreamCacheLockObj = new object();
    static readonly object sSpStreamCacheLockObj2 = new object();

    public static SpStream Get()
    {
        lock (sSpStreamCacheLockObj)
        {
            if (sSpStreamCacheFreeIdx < 0 || sSpStreamCacheFreeIdx >= sSpStreamCache.Length)
                return new SpStream();
            var tmp = sSpStreamCache[sSpStreamCacheFreeIdx];
            sSpStreamCacheFreeIdx--;
            return tmp;
        }
    }

    public static void Collect(SpStream sp)
    {
        if (sp == null)
            return;
        lock (sSpStreamCacheLockObj2)
        {
            int idx = sSpStreamCacheFreeIdx + 1;
            if (idx >= 0 && idx < sSpStreamCache.Length)
            {
                sp.Reset();
                sSpStreamCache[idx] = sp;
                sSpStreamCacheFreeIdx = idx;
            }
        }
    }
}