gpt4 book ai didi

c# - 我应该调用 GC.Collect

转载 作者:太空宇宙 更新时间:2023-11-03 19:17:21 25 4
gpt4 key购买 nike

我有一个作为 Windows 服务托管的 wcf 服务,具有以下功能:

public int SendMultipleMessages(List<Message> messages)
{
foreach (var message in messages)
{
//Do some stuff with the messages ie. get an id to return, save info in a db.
}

//Would it make sence to collect here ??
Gc.Collect();

Task.Factory.StartNew(() =>
{
//very time demanding task
_sendRequestHandler.SendMultipleMessages(BatchId);
});

return BatchId;
}

List< Message > 对象(通常)最多使用 1 gb 的内存,在这种情况下调用 GC.Collect 是否有意义,因为我不再使用该列表,或者我应该让垃圾收集器自己处理这个?

最佳答案

简短回答:

如果您调用 GC.Collect() ,你可能有问题。很少需要调用它。

在您当前的示例中,鉴于当前代码,它无济于事。除非你亲自清除 Message 的列表对象,它们将不会被垃圾回收因为调用者仍然引用 List<T> 中的对象实例。

当然,该建议是基于这样的假设,即每个 Message 都不存在其他引用资料。对象。

您可以通过从 List<T> 中删除消息对象来为您的流程添加更多确定性。一旦它们被处理,或者通过切换到一个内在体现这一原则的数据结构,例如 Queue<T>Stack<T>取决于您的订购要求。

public int SendMultipleMessages(Queue<Message> messages)
{
while (messages.Count > 0)
{
var message = messages.Dequeue();
// do something with message, and once you're done it is
// probably eligible for garbage collection because it is
// no longer in the Queue
}

Task.Factory.StartNew(() =>
{
//very time demanding task
_sendRequestHandler.SendMultipleMessages(BatchId);
});

return BatchId;
}

关于c# - 我应该调用 GC.Collect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15206119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com