C# Return Value of a Thread

Asked

Viewed 683 times

0

I created a database connection class that I intend to use Thread to make queries faster.

In office ExecutarSelect and ExecutarSQLPiece I have returns, but I couldn’t get those returns through the thread.

I did some research but I couldn’t get the solution, someone would know to help me?

Thank you very much!

// Thread instantiation and call execution

        ThreadBD thBD = new ThreadBD();
        thBD.comandoSQL = "SELECT acessoRapido FROM dbo.parametrosUsuario";
        Thread th = new Thread(thBD.executarSQLPiece);
        th.Start();

// Class of connection to the data flock

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Threading;

namespace H7Transporte
{

    class ConexaoBD
    {
        //string connection;
        DataTable tabela = new DataTable();
        string retorno;
        public ConexaoBD()
        {
        }

        public void ExecutarQuery(string comandoString)
        {
            string connectionString = "Data Source=.\\SQLServer;Initial Catalog=H7Transporte;Integrated Security=True";
            SqlConnection cnn = new SqlConnection(connectionString);
            try
            {
                cnn.Open();
                SqlCommand comando = new SqlCommand(comandoString, cnn);
                comando.ExecuteNonQuery();
            }
            catch (Exception)
            {
                MessageBox.Show("Não foi possivel executar seu comando. O Query pode estar errado ou o retorno é nulo ");

            }
            finally
            {
                cnn.Close();
            }
        }

        public DataTable ExecutarSelect(string comandoString)
        {
            string connectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=teste2;Integrated Security=True";
            SqlConnection cnn = new SqlConnection(connectionString);

            try
            {
                cnn.Open();
                SqlDataAdapter Preencher = new SqlDataAdapter(comandoString, cnn);
                Preencher.Fill(tabela);
            }
            catch (Exception)
            {
                MessageBox.Show("Nenhuma informação foi encontrada. Seu Query pode estar errado ou o retorno é nulo ");
            }
            finally
            {
                cnn.Close();
            }
            return tabela;

        }

        public string sqlPiece(string comandoString)
        {
            string connectionString = "Data Source=.\\SQLServer;Initial Catalog=H7Transporte;Integrated Security=True";
            SqlConnection cnn = new SqlConnection(connectionString);

            try
            {
                cnn.Open();
                SqlCommand comando = new SqlCommand(comandoString, cnn);
                SqlDataReader sqlReader = comando.ExecuteReader();

                sqlReader.Read();
                retorno = sqlReader.GetValue(0).ToString();

            }
            catch (Exception)
            {
                MessageBox.Show("Nenhuma informação foi encontrada. Seu Query pode estar errado ou o retorno é nulo");
            }
            finally
            {
                cnn.Close();
            }

            return retorno;
        }
    }

    class ThreadBD
    {
        public string comandoSQL { get; set; }
        public string retorno { get; set; }

        public void executarQuery()
        {
            ConexaoBD conecta = new ConexaoBD();
            conecta.sqlPiece(comandoSQL);
        }

        public void executarSelect()
        {
            ConexaoBD conecta = new ConexaoBD();
            conecta.sqlPiece(comandoSQL);
        }

        public void executarSQLPiece()
        {
            ConexaoBD conecta = new ConexaoBD();
            conecta.sqlPiece(comandoSQL);
        }
    }
}

1 answer

3

I created a database connection class that I intend to use Thread to make queries faster.

This does not make the consultations faster. It only allows you to perform queries in parallel, and the mode you use easily approaches bad practices because:

  • There is no protection of critical regions (return and connection variables);
  • No analysis of running conditions;
  • Your idea of why to use threads in this case you are mistaken.

In office ExecutarSelect and ExecutarSQLPiece I got returns, but I couldn’t get those returns through thread.

The correct way to do this is by declaring a return variable outside the Thread and making her receive the value through a delegate passed as argument:

object retorno = null;
var thread = new Thread(
    () =>
    {
        retorno = thBD.executarSQLPiece();
    });
thread.Start();
thread.Join();
// Utilize o valor de 'retorno' aqui

Browser other questions tagged

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