1
Come on . I’m loading Buttons into a panel through the Backgroundworker. That is, within this Background I execute a query in the bank through the EF and fill the panel with the Buttons that contain information from this query . The more times the thread runs, the more memory it allocates. What I do to prevent this consumption from growing so much ?
Here is the code of the Backgroundworker
private void WorkCarregaVendas_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
int i = 0;
while (true)
{
Application.DoEvents();
Application.EnableVisualStyles();
this.BeginInvoke(new MethodInvoker(() =>
{
CarregaVendasAtivas();
CarregaMesas();
CarregaDeliverys();
ExecutaPesquisaNumero(txtPesquisaNumero.Text, true);
}));
Thread.Sleep(TimeSpan.FromSeconds(30));
}
}
Here I press the buttons .
private void CarregaMesas()
{
foreach (BotaoOperacional Control in flMesas.Controls)
{
Control.Dispose();
}
flMesas.Controls.Clear();
//Pois se há uma pesquisa não a necessidade de carregar todos .
if (txtPesquisaNumero.Text.Equals(String.Empty))
foreach (var mesaCliente in objListaVendasAtivas.Where(x => x.IdTipoVenda == (int)EnumTipoVenda.Mesa).OrderBy(x => x.NumeroMesa))
{
decimal preco = 0;
using (var insRepositorioMesaProduto = new MesaProdutoRepositorio())
{
preco = insRepositorioMesaProduto.
PesquisaProdutoMesa(mesaCliente.Id).Select(x => x.Produto)
.Sum(x => x.PrecoVenda);
}
var btn = new BotaoOperacional(mesaCliente)
{
AtualizarMenuPrincipal = CarregaMesas,
Aparencia = EnumTipoVenda.Mesa,
NumeroMesa = mesaCliente.NumeroMesa,
Cliente = mesaCliente.Cliente == null ? "" : mesaCliente.Cliente.Descricao,
Preco = preco
};
btn.CarregaBotao();
flMesas.Controls.Add(btn);
}
}
Put in the question the code snippet in which you instantiate the buttons from the results of your query. Only then can someone check if by chance you are not leaving buttons allocated from previous queries (which could indicate increased memory consumption).
– Luiz Vieira
Luiz already added the code to the question .
– Felipe Laera
Executioner
WorkCarregaVendas_DoWork
? Because he has an infinite bond (while (true)
), if the (apparent) idea would just load the information and end? How do you know that the memory leak is not in the other calls (CarregaVendasAtivas();
orCarregaDeliverys();
, for example)? And what doesbtn.CarregaBotao()
? Unfortunately, there are plenty of places where there could be trouble. You tried to restrict the code (commenting) to try to find out where exactly the problem occurs?– Luiz Vieira
as @Luizvieira objected, a
while (true)
with aThread.Sleep(TimeSpan.FromSeconds(30));
it doesn’t seem healthy... you could try using aSystem.Timers.Timer
as in the example: https://dotnetfiddle.net/6mkoA5– Tobias Mesquita