为什么我应该在 DataContainer 或 DataContext 上调用 Dispose,尽管它们看起来没有区别?
我创建了一个简单的测试程序来找出为 DataContainer 对象调用 Dispose 与不调用 Dispose 之间的内存和速度差异。
这是我的测试程序:
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 5000; i++)
{
// I change the following call with Method1 and run it again
var res = Method2();
int count = res.Count;
}
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);
Console.WriteLine("Mem: " + System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64.ToString("N"));
Console.ReadKey();
}
private static IList Method1()
{
using (var db = new Model.SampleEntities())
{
var result = db.People.Where(p => p.Name.StartsWith("a")).Take(1);
return result.ToList();
}
}
private static IList Method2()
{
var db = new Model.SampleEntities();
var result = db.People.Where(p => p.Name.StartsWith("a")).Take(1);
return result.ToList();
}
两种方法的结果相同。 我的 PC 上的结果约为 27.22 秒,私有内存大小约为 37.7 MB。
现在为什么我应该为 DataContainers 调用 Dispose,而它没有不同?
提前致谢。
I create a simple test program to find out the memory and speed difference between calling Dispose vs not calling it for DataContainer object.
Here my test program:
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 5000; i++)
{
// I change the following call with Method1 and run it again
var res = Method2();
int count = res.Count;
}
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);
Console.WriteLine("Mem: " + System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64.ToString("N"));
Console.ReadKey();
}
private static IList Method1()
{
using (var db = new Model.SampleEntities())
{
var result = db.People.Where(p => p.Name.StartsWith("a")).Take(1);
return result.ToList();
}
}
private static IList Method2()
{
var db = new Model.SampleEntities();
var result = db.People.Where(p => p.Name.StartsWith("a")).Take(1);
return result.ToList();
}
The results are the same for both methods.
The result on my PC was about 27.22 seconds and about 37.7 MB of private memory size.
Now why should I call Dispose for DataContainers while it doesn't differ?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想象 Model.SampleEntities 返回 IDisposable 是有充分理由的 - 也许正确地清理了托管和/或非托管资源等
Id imagine Model.SampleEntities returns an IDisposable for a good reason - perhas properly cleaning up managed and/or unmanaged resources etc