We have a webAPI in our project which is very simple but it does not release the memory after execution and every time it is executed, it increases the used memory.
I was using webAPI 2.0 and MongoDB as back end server.
public class LogsController:ApiController
{
BsonDocument __docs;
IMongoDatabase __db;
IMongoCollection<BsonDocument> __docsColl;
[Route("api/Logs")]
public async Task<int> Post(RequestData logs)
{
if (logs.Token == "I")
{
__db = new MongoClient(new MongoClientSettings
{
Server = new MongoServerAddress("serverIP", 27017),
Credentials = new[] { MongoCredential.CreateCredential("database", "user name", "password") }
}).GetDatabase("connect_database");
__docs = new BsonDocument()
{
{ "Customer",logs.Customer}
};
__docsColl = __db.GetCollection<BsonDocument>("InsertData");
await __docsColl.InsertOneAsync(__docs);
}
logs = null;
return 1;
}
protected override void Dispose(bool disposing)
{
__docs = null;
__db = null;
__docsColl = null;
GC.SuppressFinalize(true);
base.Dispose(disposing);
}
}
I have tried all possible solutions I found, but so far no luck.
When webAPI call with the post parameters then it will deserialize into the class which is we are use as the parameters.
Further checking found that when class content the string datatype then it will use the memory and not release at a time after response return from webAPI.
If you really required memory then you must need to override Dispose method of ApiController.
Code block should be:
protected override void Dispose(bool disposing)
{
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
base.Dispose(disposing);
}
GC.Collect is not recommended method but when your posting large amount of data in parameter you must need to use this for free memory quickly.