5
I’m trying to make use of C# Threads for the first time, I’m a beginner in the subject, so I’m sorry for the question if it’s too basic. I am using the code below to use such procedure:
private Thread thread;
private void btn_ObtemClientes_Click(object sender, EventArgs e)
{
thread = new Thread(() =>
{
btn_ObtemClientes.Enabled = false;
btn_ObtemVlrContas.Enabled = true;
try
{
try
{
FbCommand command_ObtemCliente_loja7001 = new FbCommand("SELECT CLIENTES FROM CLIENTES", ConexaoAoBanco_loja7001);
ConexaoAoBanco_loja7001.Open();
reader = command_ObtemCliente_loja7001.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
dtGridView_Resultados_Busca_CtasReceber.Rows.Add(reader[0], reader[1], reader[2]);
}
}
reader.Close();
ConexaoAoBanco_loja7001.Close();
}
catch (Exception exlj7001)
{
dtGridView_Resultados_Busca_CtasReceber.Rows.Clear();
MetroFramework.MetroMessageBox.Show(this, "Erro ao gravar os dados da loja 7001 no Banco Local!\n\n" + exlj7001.Message, "ERRO!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
});
thread.Start();
}
}
But when clicking the button, the following error is returned:
System.Invalidoperationexception: 'Invalid thread operation: btn_ObtemClient control' accessed from a thread that is not the one in which it was created.'
How can I resolve such error? I researched on the subject and saw the use of delegates, and Invoker as a solution, but I don’t know how to use and I’m kind of lost in the subject sincerely.
The best tip I can give you is not to use threads, this is a crude mechanism and has better things like
async
andTask
. Hardly anyone can useThread
correctly. It is true that almost nobody does competition correctly and the most common is to use it to make the situation worse. https://answall.com/q/1946/101 Tinkering with this is extremely complicated even for those who are very experienced. Avoid. And I saw other much more basic problems in the code. This code will bring huge problems.– Maniero
I had to use threading a few days ago I used the Backgroundworker is from c# even, it is easier to implement and test since it Emit signals at the end of each step! https://docs.microsoft.com/pt-br/dotnet/api/system.componentmodel.backgroundworker?view=netframework-4.7.2
– Lodi
I really appreciate the advice... After further research on the subject, I realized that the advice for "no use" is much larger than for use. I had a wrong view of Thread usage.
– Matheus Oliveira.