C # Return Values of a Thread

-1

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

In functions ExecutarSelect and ExecutarSQLPiece I have returns, but I could not get those returns through the thread.

I did a search but could not get the solution, could someone help me?

Thank you very much!

// Instantiating and calling thread execution

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

// DataBase Connection Class

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);
        }
    }
}
    
asked by anonymous 24.02.2016 / 19:58

1 answer

2
  

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

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

  • There is no protection for critical regions (return and connection variables);
  • There is no analysis of race conditions;
  • Your idea of why threads in this case is wrong.
  

In the ExecutarSelect and ExecutarSQLPiece functions I have returns, but I could not get those returns through the thread .

The correct way to do this is by declaring a return variable outside of Thread and making it 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
    
24.02.2016 / 23:58