冗余设置为null /在调用的函数中设置为null

时间:2019-05-21 14:54:50

标签: c#

我创建了一个函数来确保正确处置对象。此功能包括将对象设置为null。我想知道将对象设置为null的行是否无用(因此我将删除该行),然后在调用函数中添加一行以将对象设置为null。我的示例是针对FileStream对象的,但是我可以使用其他任何对象(我认为)代替它。我知道我可以跟踪程序的执行情况并查看正在发生的情况,但是,我想了解有关内部机制(垃圾收集?)的更多信息,这对任何对象都有效吗?

//Called function:
public static void DiscardFile(System.IO.FileStream file)
{
    file.Flush();
    file.Close();
    file.Dispose();
    //Does this work?
    //When the function returns, is the file object really set to null?
    file = null;
}

//Calling function:
public static void WriteStringToFile(string s, string fileName)
{
    System.IO.StreamWriter file = new System.IO.StreamWriter(fileName);
    file.Write(s);
    DiscardFile(file);
    //Is this redundant?
    //Or is the line in the called function the redundant line?
    file = null;
}

谢谢!

我有一个循环,可在30秒内将一千个字符串写入文件。 (该程序完成执行时将写入400K +字符串。)我看到循环(每隔一段时间)在file.Write(s)行中等待,并且该应用程序的内存占用量增加。那是另一个线程,但是想知道上面代码的行为。

谢谢!

1 个答案:

答案 0 :(得分:2)

对不起,但是您的实现是危险

DEFAULT

假设您在CREATE FUNCTION vw_table_ab_insert(new vw_table_ab) RETURNS void LANGUAGE plpgsql AS $_$ DECLARE id_table_a integer; BEGIN IF new.timestamp_a IS NULL THEN new.timestamp_a = DEFAULT; END IF; IF new.boolean_a IS NULL THEN new.boolean_a = DEFAULT; END IF; IF new.timestamp_b IS NULL THEN new.timestamp_b = DEFAULT; END IF; IF new.boolean_b IS NULL THEN new.boolean_b = DEFAULT; END IF; INSERT INTO table_a (timestamp_field, boolean_field) VALUES (new.timestamp_a, new.boolean_a) RETURNING id INTO id_table_a; INSERT INTO table_b (timestamp_field, boolean_field, id_table_a) VALUES (new.timestamp_a, new.boolean_b, id_table_a); END; $_$; 上引发了异常,这意味着public static void WriteStringToFile(string s, string fileName) { System.IO.StreamWriter file = new System.IO.StreamWriter(fileName); file.Write(s); // <- the danger is here DiscardFile(file); //Is this redundant? Yes, it's redundant //Or is the line in the called function the redundant line? file = null; } 将永远不会被执行,因为您有资源泄漏file.Write(s);-打开的文件句柄) 。 为什么不坚持标准 DiscardFile(file);模式:

HFILE

对于 C#8.0 ,您可以摆脱烦人的using,并让系统在离开方法的作用域时释放资源(请参见https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations ):

public static void WriteStringToFile(string s, string fileName) 
{
    // Let system release all the resources acquired 
    using var file = new System.IO.StreamWriter(fileName); 
    {
        file.Write(s);
    }  // <- here the resources will be released
}