XAML with parameter - BackgroundWorker

3

I'm making a small XAML application that requests 2 dates. Dates are passed as a parameter to some methods invoked by the Button click event. The problem is that during the execution of the methods the form remains locked.

How to use the BackgroundWorker or other Threads feature to solve this problem?

privatevoidButton_Click(objectsender,RoutedEventArgse){DateTimedataInicial=newDateTime();DateTimedataFinal=newDateTime();dataInicial=(DateTime)dtInicial.SelectedDate;dataFinal=(DateTime)dtFinal.SelectedDate;progressbar1.Visibility=Visibility.Visible;progressbar1.IsIndeterminate=true;thread=newThread(()=>{relatorio1r1=newrelatorio1();r1.gerarDados(dataInicial,dataFinal);relatorio2r2=newrelatorio2();r2.gerarDados(dataInicial,dataFinal);relatorio3r3=newrelatorio3();r3.gerarDados(dataInicial,dataFinal);relatorio4r4=newrelatorio4();r4.gerarDados(dataInicial,dataFinal);MessageBox.Show("Sucesso !!!");          

    });

    thread.Start();
    progressbar1.IsIndeterminate = false;




}

In the current code I solved the crash problem by instantiating a Thread directly through Lambda. The problem is that I can not change the ProgressBar properties of the Form as soon as the Thread ends. I would like to set the IsIndeterminate event to false but I did not succeed. I believe Backgroundworker is possible.

    
asked by anonymous 19.02.2016 / 15:00

1 answer

1

The solution to this problem is much simpler than that. Including, one of the biggest advantages of C # is how easy you can work with asynchronous methods without manually managing threads.

All you need to do is start the method where all processing occurs in Task and expect it to finish using await . Look how the new version of your code looks like:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var beginDate = begin.SelectedDate;
    var endDate = end.SelectedDate;

    progressBar.Visibility = Visibility.Visible;
    progressBar.IsIndeterminate = true;

    await Task.Run(() =>
    {
        relatorio1 r1 = new relatorio1();
        r1.gerarDados(beginDate , endDate);
        relatorio2 r2 = new relatorio2();
        r2.gerarDados(beginDate , endDate);
        relatorio3 r3 = new relatorio3();
        r3.gerarDados(beginDate , endDate);
        relatorio4 r4 = new relatorio4();
        r4.gerarDados(beginDate , endDate);

    });

    MessageBox.Show("Sucesso!");
    progressBar.Visibility = Visibility.Collapsed;
}

Only one addendum: In the current version of the code, you can click the button multiple times while processing occurs, which would cause reports to be generated multiple times. To resolve this you can use either a lock or simply disable the button while processing is not complete.

    
19.02.2016 / 17:46