c#Lazy懒加载详细解读及其例子
程序员文章站
2022-05-21 22:12:54
...
近期接到个需求要求不准使用分页控件使用滚动条的方式加载出来几十万条数据,还不能影响性能。
固把Lazy再次看了一遍
static void Main(string[] args)
{
//不使用延迟加载例子
//Stopwatch win7Stopwatch = Stopwatch.StartNew();
//win7Stopwatch.Start();
//Windows7 win7 = new Windows7(1);
//win7Stopwatch.Stop();
//Console.WriteLine($"win7时间{win7Stopwatch.Elapsed}]");
//使用延迟加载例子
//Stopwatch win10Stopwatch = Stopwatch.StartNew();
//win10Stopwatch.Start();
//Windows10 windows10 = new Windows10(1);
//win10Stopwatch.Stop();
//Console.WriteLine($"win10是否初始化[{windows10.SoftWares.IsValueCreated}]");
//Console.WriteLine($"win10时间:[{win10Stopwatch.Elapsed}]");
//List<SoftWare> SoftWares = windows10.SoftWares.Value;//此时使用的时候才会真正的去跑下面那个循环
//Console.WriteLine($"win10是否初始化[{windows10.SoftWares.IsValueCreated}]");
//思考懒加载加分页混合使用
//不使用延迟加载例子加模拟分页
Stopwatch win7Stopwatch = Stopwatch.StartNew();
win7Stopwatch.Start();
Windows7 win7 = new Windows7(1);
win7Stopwatch.Stop();
Console.WriteLine($"win7时间{win7Stopwatch.Elapsed}]");
//使用延迟加载例子加模拟分页
Stopwatch win10Stopwatch = Stopwatch.StartNew();
win10Stopwatch.Start();
Windows10 windows10 = new Windows10(1);
List<SoftWare> SoftWares = windows10.SoftWares.Value;//此时使用的时候才会真正的去跑下面那个循环
win10Stopwatch.Stop();
Console.WriteLine($"win10是否初始化[{windows10.SoftWares.IsValueCreated}]");
Console.WriteLine($"win10时间:[{win10Stopwatch.Elapsed}]");
Console.Read();
}
/// <summary>
/// win7电脑开机很慢
/// </summary>
public class Windows7
{
public int Id { get; private set; }
//不使用延迟加载,解除上面注释切换使用延迟加载
public List<SoftWare> SoftWares { get; set; }
public Windows7(int id)
{
this.Id = id;
//不使用延迟加载,解除上面注释切换使用延迟加载
SoftWares = SoftWareRepository.GetSoftWaresByID(1);
Console.WriteLine("win7初始化");
}
}
/// <summary>
/// win10电脑开机很快
/// </summary>
public class Windows10
{
public int Id { get; private set; }
//使用延迟加载
public Lazy<List<SoftWare>> SoftWares { get; set; }
public Windows10(int id)
{
this.Id = id;
//使用延迟加载
SoftWares = new Lazy<List<SoftWare>>(() => SoftWareRepository.GetSoftWaresByID(1));
Console.WriteLine("win10初始化");
}
}
public class SoftWare
{
public int Id { get; set; }
public string Title { get; set; }
}
public class SoftWareRepository
{
public static List<SoftWare> GetSoftWaresByID()
{
List<SoftWare> softWares = new List<SoftWare>();
for (var i = 0; i < 10000000; i++)
{
softWares.Add(new SoftWare()
{
Id = i,
Title = "Lazytitle" + i
});
}
return softWares;
}
public static List<SoftWare> GetSoftWaresByID(int page)
{
List<SoftWare> softWares = new List<SoftWare>();
for (var i = page*100000+1; i < (page+1) * 100000; i++)
{
softWares.Add(new SoftWare()
{
Id = i,
Title = "Lazytitle" + i
});
}
return softWares;
}
上一篇: 北京公园有哪些 北京公园盘点
推荐阅读