Denis Denis - 26 days ago 12
C# Question

WPF C# Progress Bar different Window

I´m trying to figure out how to implement a progress bar in my application.

I´ve read some articles like this How to correctly implement a BackgroundWorker with ProgressBar updates?, and I caught how it works. My doubt is how will I call and update the progressbar.xaml since I´m executing the sql in the PendenciaController.cs.

PendenciaConsulta.xaml.cs

Task.Factory.StartNew(() =>
{
Progress<long> progress = null;

progress = new Progress<long>((i) =>
{
try
{
Dispatcher.Invoke(() => { PBar.Value = i; });
}

catch { }
});

pendenciaController = new PendenciaController(progress);
pendenciaController.PendenciaConsultar((bool)chkFollowUp.IsChecked); //The error occurs here

pendenciaController.PopularListas();

StatusController statusController = new StatusController();
ObservableCollection<Status> ListaStatus = null;
dataContext = new DataContext();
this.listaPendencia = this.pendenciaController.ListaPendencia;
ListaStatus = statusController.StatusConsultar();
this.DataContext = dataContext;
dtgPendencia.ItemsSource = this.listaPendencia;
lblQuantidadeRegistros.Content = "Quantidade de registros: " + this.listaPendencia.Count;

PopularCombos();
});


PendenciaController.cs

private Progress<long> _progress;

public PendenciaController(Progress<long> progress)
{
_progress = progress;
}

public void PendenciaConsultar(bool followUp)
{
OleDbConnection conn = null;

#region Select e conversão do DataSet
try
{
conn = new OleDbConnection(Conexao.getConexao());
conn.Open();

//Select da tabela tblPendencia
StringBuilder cmd = new StringBuilder();

cmd.Append("SELECT P.pendenciaId, " +
" P.contrato, " +
" P.adAm, " +
" P.diasDecorridos, " +
" P.corretora, " +
" P.produto, " +
" P.clienteNome, " +
" P.clienteCnpj, " +
" P.aberturaData, " +
" P.pendenciaTipo, " +
" P.lastro, " +
" P.garantiaDescricao, " +
" P.observacao, " +
" P.vencimentoData, " +
" P.liquidacaoData, " +
" P.rating, " +
" P.operacaoValor, " +
" P.pendenciaNivel, " +
" P.pendenciaValorFator, " +
" P.porContrato, " +
" P.officer, " +
" P.centroCusto, " +
" P.isCritico, " +
" P.statusId, " +
" P.clienteGrupo, " +
" P.followUp, " +
" P.carenciaInicio, " +
" P.carenciaFim, " +
" P.moeda, " +
" P.documentoTipo, " +
" P.tipo, " +
" (SELECT S.statusDescricao " +
" FROM tblStatus S " +
" WHERE S.statusId = P.statusId) as statusDescricao" +
" FROM tblPendencia P");

if (!followUp)
{
cmd.Append(" WHERE ((P.followUp <= NOW()) " +
" OR (P.followUp IS NULL))");
}
else
{
cmd.Append(" WHERE ((P.followUp <= NOW()) " +
" OR (P.followUp >= NOW()) " +
" OR (P.followUp IS NULL))");
}


OleDbDataAdapter da = new OleDbDataAdapter(cmd.ToString(), conn);

DataSet ds = new DataSet();
da.Fill(ds, "tblPendencia");
DataTable dt = new DataTable();
dt = ds.Tables["tblPendencia"];

Pendencia pendencia = null;

this.ListaPendencia = new List<Pendencia>();

if (ds.Tables != null && ds.Tables[0].Rows.Count > 0)
{
//foreach (DataRow dtRow in ds.Tables[0].Rows)
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow dtRow = ds.Tables[0].Rows[i];

pendencia = new Pendencia();

pendencia.AberturaData = dtRow["aberturaData"].ToString();
pendencia.AdAm = dtRow["adAm"].ToString();
pendencia.CentroCusto = dtRow["centroCusto"].ToString();
pendencia.ClienteCnpj = dtRow["clienteCnpj"].ToString();
pendencia.ClienteNome = dtRow["clienteNome"].ToString();
pendencia.Contrato = dtRow["contrato"].ToString();
pendencia.Corretora = dtRow["corretora"].ToString();
pendencia.DiasDecorridos = dtRow["diasDecorridos"].ToString();
pendencia.GarantiaDescricao = dtRow["garantiaDescricao"].ToString();
pendencia.Lastro = dtRow["lastro"].ToString();
pendencia.LiquidacaoData = dtRow["liquidacaoData"].ToString();
pendencia.Observacao = dtRow["observacao"].ToString();
pendencia.Officer = dtRow["officer"].ToString();
pendencia.OperacaoValor = dtRow["operacaoValor"].ToString();
pendencia.PendenciaId = Convert.ToInt32(dtRow["pendenciaId"]);
pendencia.PendenciaNivel = dtRow["pendenciaNivel"].ToString();
pendencia.PendenciaValorFator = dtRow["pendenciaValorFator"].ToString();
pendencia.StatusId = String.IsNullOrEmpty(dtRow["statusId"].ToString()) ? 0 : Convert.ToInt32(dtRow["statusId"]);
pendencia.Produto = dtRow["produto"].ToString();
pendencia.Rating = dtRow["rating"].ToString();
pendencia.PendenciaTipo = dtRow["pendenciaTipo"].ToString();
pendencia.VencimentoData = dtRow["vencimentoData"].ToString();
pendencia.ClienteGrupo = dtRow["clienteGrupo"].ToString();
pendencia.FollowUp = dtRow["followUp"].ToString();
pendencia.CarenciaInicioData = dtRow["carenciaInicio"].ToString();
pendencia.CarenciaFimData = dtRow["carenciaFim"].ToString();
pendencia.DocumentoTipo = dtRow["documentoTipo"].ToString();
pendencia.StatusDescricao = dtRow["statusDescricao"].ToString();
pendencia.PorContratoDescricao = dtRow["porContrato"].ToString();
pendencia.Moeda = dtRow["moeda"].ToString();
pendencia.Tipo = dtRow["tipo"].ToString();

pendencia.IsCritico = Convert.ToBoolean(dtRow["isCritico"]);
pendencia.StatusId = String.IsNullOrEmpty(dtRow["statusId"].ToString()) ? 0 : Convert.ToInt32(dtRow["statusId"]);

this.ListaPendencia.Add(pendencia);

((IProgress<long>)(_progress)).Report((long)i);

}
}
}

catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

finally { conn.Close(); }
#endregion
}


Thanks.

Answer

You should use Progress<T> Class and Task.

Example :

public partial class Window25 : Window
{
    public Window25()
    {
        InitializeComponent();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        Task.Factory.StartNew(() =>
        {
            Progress<long> progress = null;
            progress = new Progress<long>((i) =>
            {
                try
                {
                    // Update ProgressBar 
                    Dispatcher.Invoke(() => { PBar.Value = i; });
                }
                    // handle pre-mature closing of window (task cancellation)
                catch { }
            });

            Controller c = new Controller(progress);
            c.Do();
        }
        );
    }
}

public class Controller
{
    Progress<long> _progress;
    public Controller(Progress<long> progress)
    {
        _progress = progress;
    }

    public void Do()
    {
        for (long s = 0; s < 99999; ++s)
            ((IProgress<long>)(_progress)).Report((long)s);
    }
}

Progress class

Async in 4.5: Enabling Progress and Cancellation in Async APIs

See if this solves your problem.

Comments