Progress bar for stored procedure in C # windows form

1

I have a project that updates data through a stored procedure (delete, insert, update) with undefined long duration. I would like to display a progress bar with undetermined time during the procedure execution period. I have no experience in progress bar. Can anyone explain how to implement it?

private void btActualizar_Click(object sender, EventArgs e)
{
    _IDSave = _ID;
    _CartaoSave = _Cartao;

    // Chama o form onde se escolhe o ano de Contabilidade (cada ano um database!)
    frmEscolhaDeAnoContabilidade frmRefresh = new frmEscolhaDeAnoContabilidade();
    frmRefresh.ShowDialog();

    string dataBaseName = frmRefresh.dataBaseName;
    string anoContabilidade = frmRefresh.anoContabilidade;

    if (dataBaseName.Length > 0)
    {
        string timeRefresh; 
        string deletedRec;
        string newRec;
        string updatedRec;
        string errorMessage;

        string resultText;

        // Tornar visivel e por a funcionar a barra de progresso
        progressBarRefresh.Visible = true;

        progressBarAdatfrissites.Show(); // É necessário?


        // Chamo assim o procedimento armazenado
        General2.RefreshCartaoByYear(dataBaseName);

        // Findar a barra de progresso

        if (General2.DsRefreshCartaoByYear.Tables[0].Rows.Count > 0)
        {
            timeRefresh = General2.RefreshCartaoByYear.Tables[0].Rows[0]["TimeRefresh"].ToString();
            deletedRec = General2.RefreshCartaoByYear.Tables[0].Rows[0]["DeletedRec"].ToString();
            newRec = General2.RefreshCartaoByYear.Tables[0].Rows[0]["NewRec"].ToString();
            updatedRec = General2.RefreshCartaoByYear.Tables[0].Rows[0]["UpdatedRec"].ToString();
            errorMessage = General2.RefreshCartaoByYear.Tables[0].Rows[0]["ErrorMessage"].ToString();

            if (errorMessage.Length > 0)
            {
                resultText = "Sem resultado! \n" +
                             "Erro: " + errorMessage;
            }
            else
            {
                resultText = "Frissítés eredmény: \n" + 
                             "Időpont: " + timeRefresh + ", Könyvelési év: " + konyvalesiEv + "\n" +
                             "Törölt tételek száma: " + deletedRec + ", Új teételek száma: " + newRec + ", Módosult tételek száma: " + updatedRec;
            }

            MessageBox.Show(resultText);

            AktualiyarDataGridView();

            dgvCartao.Rows
                      OfType<DataGridViewRow>()
                      .Where(x => x.Cells["ID"].Value.ToString() == _IDSave)
                      .ToArray<DataGridViewRow>()[0]
                       .Selected = true;
        }
    }
}


namespace Total_accounts
{
  class General2
  {
    public static void RefreshCartaoByYear( string _Database)
    {
        SqlCommand commSQLCommand = new SqlCommand();
        SqlDataAdapter daSqlDataAdapter = new SqlDataAdapter();
        SqlCommandBuilder cbSQLCommandBuilder = new SqlCommandBuilder();
        SqlConnection connSQLServer1 = new SqlConnection();
        SqlDataReader dataSQLDataReader = null;

        dsRefreshCartaoByYear = new DataSet();

        try
        {
            connSQLServer1.ConnectionString = General.STRConnection; //strConnection;
            connSQLServer1.Open();
            commSQLCommand.Connection = connSQLServer1;
            commSQLCommand.CommandType = CommandType.StoredProcedure;
            commSQLCommand.CommandText = "spRefreshCartaoByYear";

            commSQLCommand.CommandTimeout = timeOut;

            daSqlDataAdapter.SelectCommand = commSQLCommand;
            cbSQLCommandBuilder.DataAdapter = daSqlDataAdapter;

            dsRefreshCartaoByYear.Clear();
            commSQLCommand.Parameters.AddWithValue("@strpmDatabase", _Database);
            daSqlDataAdapter.Fill(dsRefreshCartaoByYear, "tableRefreshCartaoByYear");
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
        }
        finally
        {
            if (connSQLServer1 != null)
            {
                connSQLServer1.Close();
            }
            if (dataSQLDataReader != null)
            {
                dataSQLDataReader.Close();
            }
        }
    }
  }
}
    
asked by anonymous 07.06.2018 / 20:41

1 answer

0

You can use an asynchronous task to perform a long procedure. This can be done as follows:

Add a return of type "System.Threading.Tasks.Task" in the method that performs the long procedure so that it can be 'awaitable' / waitard:

public async Task MeuProcedimentoLongo()
{
  // código...
}

So you could call the procedure elsewhere:
public async void MeuMetodo() 
{
    // criacao e inicializacao da ProgressBar
    var pb = new ProgressBar();
    pb.Style = ProgressBarStyle.Marquee;
    pb.Visible = true;

    // aguarde o metodo realizar o procedimento longo
    await MeuProcedimentoLongo();
    pb.Visible = false;
}

Or you could call it by task delegation:

public void MeuMetodo()
{
    // criacao e inicializacao da ProgressBar

    // aguarde a tarefa ser realizada
    Task.Run(async ()=> { await MeuProcedimentoLongo(); });
}
  

Note also that the reserved word async is used when you want to wait for a task within a method!

    
19.09.2018 / 17:08