Reputation: 95
I have a wcf service hosted as a windows service with the following function:
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;
}
The List< Message > object (more often than not) uses up to 1 gb of memory, would it make sense to call GC.Collect in a situation like this, since im not using the list anymore, or should i let the Garbage collector handle this on its own ?
Upvotes: 1
Views: 570
Reputation: 64148
Short answer: No.
If you call GC.Collect()
, you probably have a problem. It is exceedingly rare to need to call this.
In your current example, it will not help given the current code. Unless you physically clear the list of Message
objects, they will not be garbage collected because the caller still has references to the objects in that List<T>
instance.
Of course that advice is based on the assumption that no other references exist to each Message
object.
You could potentially add some more determinism to your process by removing the message objects from the List<T>
once they have been processed, or by switching to a data structure which embodies this principle inherently such as a Queue<T>
or Stack<T>
depending on your ordering requirements.
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;
}
Upvotes: 5
Reputation: 16423
Let the GC manage itself, it will be optimized differently on each machine depending on available resources etc. All you are likely to do by calling it yourself is hurt the performance of your application.
Upvotes: 1