在下面的程序中,将new myclass()动态的赋值给a1,然后执行a1.dosomething(),如果在dosomething()中使用了非托管资源,由于myclass没有释放资源,会不会产生内存泄露?非托管资源应放在myclass的什么地方释放, 如何处理这一类的问题?退一步说,就算dosomething()没有使用非托管资源,由于.net不能显示的释放对象,循环语句会大量的占用系统资源,运行会非常慢?using System;namespace Project2
{
/// <summary>
/// Summary description for Class.
/// </summary>
class Class
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
myclass a1;
for(int i=0; i<=10000;i++){
a1=new myclass();
a1.dosomething();
}
} } class myclass {
public void dosomething(){
//...
//...
}
}
}
{
/// <summary>
/// Summary description for Class.
/// </summary>
class Class
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
myclass a1;
for(int i=0; i<=10000;i++){
a1=new myclass();
a1.dosomething();
}
} } class myclass {
public void dosomething(){
//...
//...
}
}
}
就算dosomething()没有使用非托管资源,由于.net不能显示的释放对象,循环语句会大量的占用系统资源,运行会非常慢?
-----------------------------
不会慢的,CLR会管理你的内存,当它认为有必要销毁对象时,它会销毁并释放内存,很多非托管语言
需要手动销毁对象,频繁销毁对象并使可用内存大小频繁变化,往往会降低效率
for(int i=0; i<=10000;i++){
if a1!=null {
a1.dispose();
}
a1=new myclass();
a1.dosomething();
}
因为 a1这个对象创建后,会作不少工作,所以在程序中不太好确定什么时候释放资源,所以在a1=new myclass()语句之前加一个判断,如果a1!=null,则代表它正指向一个对象,先调用它的析构方法dispose释放,上面的方法行不行,有没有更好的方法
而且应当是在a1.dosomething之后就释放,不要期待CLR会在a1超出作用域后
自动替你销毁非托管资源。
for(int i=0; i<=10000;i++){
if a1!=null {
a1.dispose();
}
a1=new myclass();
a1.dosomething();
}
for(int i=0; i<=10000;i++)
{
a1.dosomething();
}
if a1!=null
{
a1.dispose();
}