Inquiridor
Count gastando muita memória

Pergunta
-
Pessoal,
Tenho uma aplicação desktop utilizando LINQ e EF4 pra comunicar numa base SQL CE 4. Estive notando que a mémoria da aplicação tem crescido por volta de 12 mb por hora. Como a aplicação deveria funcionar 24/7 isso tem feito ela parar por falta de memória depois de um tempo. Usando o Profiler de memória do VS notei que metade da memoria alocada está em alguns dos 2 counts que é dado na aplicação. Vocês sabem pq o count está alocando tanta memória? Alguem tem alguma ideia pra me ajudar?
Todas as Respostas
-
Olá Thiago,
Vc esta chamando o método ToList antes do Count?
Para responder essa pergunta preciso ver a sua query LINQ. Tem como?
[]s!
Fernando Henrique Inocêncio Borba Ferreira
Microsoft MVP - Data Platform Development
while(alive){ this.WriteCode(); }
Blog: http://ferhenriquef.com/
Twitter: @ferhenrique
Entity Framework - Brasil: https://www.facebook.com/EntityFrameworkBrasil -
Olá Fernando!
Obrigado pela resposta!
Segue o método com o count com mais memória alocada.
private static void ListFileEndNextFile(Modules module) { bool hasNext = false; PendingListFile nextListFile = new PendingListFile(); lock (_PendingListFile) { var nexts = ( from n in _PendingListFile where n.Instance == module.Instance orderby n.Channel ascending select n); hasNext = nexts.Count() > 0; if (hasNext) { nextListFile = ( from n in nexts where n.Instance == module.Instance orderby n.Channel ascending select n).First(); _PendingListFile.Remove(nextListFile); } } //Testa se ainda existe algum ListFile pendente do modulo if (hasNext) { //Se existir, chama o proximo list StringBuilder buffer = new StringBuilder(); if (LibV4._ListFileV4(nextListFile.Instance, nextListFile.Channel, nextListFile.StartYear, nextListFile.StartMonth, nextListFile.StartDay, nextListFile.EndYear, nextListFile.EndMonth, nextListFile.EndDay)) { buffer.Append("Listando arquivos do módulo "); } else { buffer.Append("Falha ao listar arquivos do módulo "); } buffer.Append(module.Name); buffer.Append(" no canal "); buffer.Append(nextListFile.Channel); buffer.Append(" de "); buffer.Append((new DateTime(nextListFile.StartYear, nextListFile.StartMonth, nextListFile.StartDay)).ToString("dd/MM/yyyy")); buffer.Append(" até "); buffer.Append((new DateTime(nextListFile.EndYear, nextListFile.EndMonth, nextListFile.EndDay)).ToString("dd/MM/yyyy")); buffer.Append("."); Status.AddMessage(buffer.ToString()); } else { //Se não existir, salva no banco e limpa a variavel IEnumerable<Files> newFiles; lock (_FilesInListFile) { newFiles = (from f in _FilesInListFile where f.FkModule == module.Id select f).ToList(); _FilesInListFile.RemoveAll(x => newFiles.Contains(x)); } lock (_dbLock) using (VeoSyncEntities entities = new VeoSyncEntities(ConnectionString)) { foreach (Files item in newFiles) { int fileExists = (from f in entities.Files where f.Channel == item.Channel && f.FileSize == item.FileSize && f.DateTimeStart == item.DateTimeStart && f.DateTimeStop == item.DateTimeStop select f).Count(); if (fileExists == 0) entities.Files.AddObject(item); } entities.SaveChanges(); } StartDownload(module); } }
Você tem alguma ideia do que pode ser ?
Existe algum método mais performático para testar se existe o registro com essas condições antes de pegar o First?
Tentei usar o FirstOrDefault mas tive problemas (que já não lembro o que foi, rs)Obrigado pela atenção!!
-
Pessoal,
Andei lendo tambem que fazer como eu faço com a variavel nextListFile faz que com o dispose não libere o contexto (pq o conteudo da nextListFile está vinculado a ele).
Alguém sabe me dizer se isso é verdade e como posso contornar isso?
Obrigado pela atenção!!
-
Olá Thiago,
Para o seu caso o FirstOrDefault seria o ideal, pois ele não dispara uma exception quando a quantidade é zero e é mais performático.
O Count é o cara que vai realizar a sua consulta, talvez essa pesquisa pela propriedade Instance seja bastante pesada. Que tipo de dados é essa propriedade?
[]s!
Fernando Henrique Inocêncio Borba Ferreira
Microsoft MVP - Data Platform Development
while(alive){ this.WriteCode(); }
Blog: http://ferhenriquef.com/
Twitter: @ferhenrique
Entity Framework - Brasil: https://www.facebook.com/EntityFrameworkBrasil- Sugerido como Resposta Fernando Henrique Inocêncio Borba FerreiraMicrosoft employee, Moderator segunda-feira, 1 de outubro de 2012 12:26
-
Fernando,
O Instance é um inteiro!
Como eu descubro se o resultado foi retornado o First ou o Default? No caso do Default seria o objeto porem nulo?
E o .Any()? Poderia usar ao invés do .Count() tambem. Me parece mais indicado usar o FirstOrDefault no primeiro caso e o Any no segundo. O que me diz?
Obrigado pela atenção!!
-
Olá Thiago,
Para rescobrir se foram retornados resultados vc teria de fazer algo como:
hasNext = (nexts.FirstOrDefault() != null);
No segundo caso vc tb pode usar o FirstOrDefault, fazendo assim:
var fileExists = (from f in entities.Files where f.Channel == item.Channel && f.FileSize == item.FileSize && f.DateTimeStart == item.DateTimeStart && f.DateTimeStop == item.DateTimeStop select f).FirstOrDefault(); if (fileExists == null) entities.Files.AddObject(item); .
[]s!Fernando Henrique Inocêncio Borba Ferreira
Microsoft MVP - Data Platform Development
while(alive){ this.WriteCode(); }
Blog: http://ferhenriquef.com/
Twitter: @ferhenrique
Entity Framework - Brasil: https://www.facebook.com/EntityFrameworkBrasil- Sugerido como Resposta Fernando Henrique Inocêncio Borba FerreiraMicrosoft employee, Moderator segunda-feira, 1 de outubro de 2012 12:26
-
Olá Thiago,
Alguma evolução nessa thread?
[]s!
Fernando Henrique Inocêncio Borba Ferreira
Microsoft MVP - Data Platform Development
while(alive){ this.WriteCode(); }
Blog: http://ferhenriquef.com/
Twitter: @ferhenrique
Entity Framework - Brasil: https://www.facebook.com/EntityFrameworkBrasil