WeakReference-弱引用


http://msdn.microsoft.com/zh-cn/library/0xy59wtx%28v=vs.90%29.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication11
{
public class Program
{

public static void Main()
{

// Create the cache.
int cacheSize = 50;
Random r = new Random();
Cache c = new Cache(cacheSize);

string DataName = "";

// Randomly access objects in the cache.
for (int i = 0; i < c.Count; i++)
{
int index = r.Next(c.Count);

// Access the object by
// getting a property value.
DataName = c[index].Name;
}
// Show results.
double regenPercent = c.RegenerationCount * 100 / c.Count;
Console.WriteLine("Cache size: {0}, Regenerated: {1}%", c.Count.ToString(), regenPercent.ToString());

}
}


public class Cache
{
// Dictionary to contain the cache.
static Dictionary<int, WeakReference> _cache;

// Track the number of times an
// object is regenerated.
int regenCount = 0;

public Cache(int count)
{

_cache = new Dictionary<int, WeakReference>();

// Add data objects with a
// short weak reference to the cache.
for (int i = 0; i < count; i++)
{
_cache.Add(i, new WeakReference(new Data(i), false));
}

}

// Returns the number of items in the cache.
public int Count
{
get
{
return _cache.Count;
}
}

// Returns the number of times an
// object had to be regenerated.
public int RegenerationCount
{
get
{
return regenCount;
}
}

// Accesses a data object from the cache.
// If the object was reclaimed for garbage collection,
// create a new data object at that index location.
public Data this[int index]
{
get
{
// Obtain an instance of a data
// object from the cache of
// of weak reference objects.
Data d = _cache[index].Target as Data;
if (d == null)
{
// Object was reclaimed, so generate a new one.
Console.WriteLine("Regenerate object at {0}: Yes", index.ToString());
d = new Data(index);
regenCount++;
}
else
{
// Object was obtained with the weak reference.
Console.WriteLine("Regenerate object at {0}: No", index.ToString());
}

return d;
}

}

}


// This class creates byte arrays to simulate data.
public class Data
{
private byte[] _data;
private string _name;

public Data(int size)
{
_data = new byte[size * 1024];
_name = size.ToString();
}

// Simple property.
public string Name
{
get
{
return _name;
}
}

}


} 优质内容筛选与推荐>>
1、在requirejs中使用qunit
2、qgis 编译
3、线程方法Bitmap 处理之不要在UI主线程中处理Bitmap
4、ora-12170:tns连接超时
5、silverlight中3D引擎Release了


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号