Help with threards system

0

I wrote a small application in C #, where its main process takes a long time to run. I'm having a problem with the lack of response from the application GUI during the execution of this process. Through help obtained here in stackoverflow , I was helped to create a thread to execute this process. However, I'm still experiencing this problem of non-response of the application during the long process.

Look how I did it:

 private void GeraRelatorio_Click(object sender, RoutedEventArgs e)
 {
      Thread geraRelatorio = new Thread(GeraRelatorio_Thread);
      geraRelatorio.SetApartmentState(ApartmentState.STA);
      geraRelatorio.Start();
      return;
 }

I'm still going to study about threads , but the problem has come before the time. Does anyone know how I make the interface respond during the process?

    
asked by anonymous 01.05.2017 / 18:57

2 answers

1

An easier way to work with threads is with Task

Your method would look like this:

private async void GeraRelatorio_Click(object sender, RoutedEventArgs e)
{
    await Task.Run(() => GeraRelatorio_Thread());           
}

With Task you need to inform that your method is an asynchronous method by inserting in the method signature the word async .

Within your method you initialize Task with method Task.Run() passing Action and within Action you call your method that will run on a thread.

The word await , roughly, causes execution control to be returned to the thread that called the async method.

For more information:

Difference between Task and Thread

MSDN

    
01.05.2017 / 19:55
0

In addition to the Task, you can use backgroundWorker.

When you access something from the interface, to get or set, you will have to use a dispatcher to access through the ui thread, if your running thread is first level, I mean, if the main thread was who the started:

private void GeraRelatorio_Click(object sender, RoutedEventArgs e){
    var bw = new BackgroundWorker();    
    bw.DoWork += delegate (object s, DoWorkEventArgs args)
    {
        GeraRelatorio_Thread();
    };
    bw.RunWorkerCompleted += delegate (object s, RunWorkerCompletedEventArgs args)
    {
        //acabou a execução, mas tu pode obter retorno de métodos e etc, fechar um loader...
    };
    bw.RunWorkerAsync();

}


private void GeraRelatorio_Thread(){
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
                    {
                        //aplica as alterações na ui
            grid.Clear() //por exemplo
                    }));

    ... //outras coisas que seu método executa
}
    
02.05.2017 / 22:24