Using C# Threads for the First Time

Asked

Viewed 456 times

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.'inserir a descrição da imagem aqui

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.

  • 2

    The best tip I can give you is not to use threads, this is a crude mechanism and has better things like async and Task. Hardly anyone can use Threadcorrectly. 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.

  • 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

  • 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.

1 answer

4


If you really have to threads, then do the following:

private Thread thread;

private void btn_ObtemClientes_Click(object sender, EventArgs e)
{
    thread = new Thread(() =>
    {
        btn_ObtemClientes.Invoke(new Action(() =>
        {
            btn_ObtemClientes.Enabled = false;
        }));

        btn_ObtemVlrContas.Invoke(new Action(() =>
        {
            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())
                    {
                        dataGridView1.Invoke(new Action(() =>
                        {
                            dtGridView_Resultados_Busca_CtasReceber.Rows.Add(reader[0], reader[1], reader[2]);
                        }));
                    }
                }

                reader.Close();
                ConexaoAoBanco_loja7001.Close();
            }
            catch (Exception exlj7001)
            {
                dataGridView1.Invoke(new Action(() =>
                {
                    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();
}

Anyway, the management of threads is quite difficult, beyond what the debug sometimes can be a nightmare, so it is recommended to "turn" to other options, as said the @Maniero, Async and Task.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.