question

babluplanet-4009 avatar image
0 Votes"
babluplanet-4009 asked DaisyTian-1203 edited

C# - How not make WPF UI Freeze while elaborating

I have a button that after I click it send a lot of data in a remote database with a loop, but during this operation whole wpf UI is freezing. My goal is to make the loader work while it is processing everything with the database. My button code:

  private void btn_Start_Click(object sender, RoutedEventArgs e)
         {
             pb_loader.IsIndeterminate = true; //<- it has to start to make animation
    
             IEmailService emailService = new EmailService();
             IUserQueryService emailQueryService = new UserQueryService();
             var idIniziale = int.Parse(txtIdIniziale.Text);
             var idFinale = int.Parse(txtIdFinale.Text);
             var n = idFinale - idIniziale;
             string mail = "";
             for(int i=0; i<=n; i++)
             {
                 mail = txtMail.Text + idIniziale + "@mail.local";
                 var exist = emailQueryService.CheckUserExist(mail); //<- db operation method
                 if (exist == false)
                 {
                    var lastUniqueId = emailQueryService.GetLastUniqueId();//<- db operation method
                    lastUniqueId = lastUniqueId + 1;
                    var idUtente = emailService.SalvaUtente(mail, lastUniqueId); //<- db operation method
                    emailService.AssegnaReferente(idUtente, txtMail.Text);//<- db operation method
                    emailService.AssegnaRuoli(idUtente); //<- db operation method
    
                 }
                 idIniziale++;
             }
             pb_loader.IsIndeterminate = false; //<- it has to end animation of loading
         }


windows-wpf
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@babluplanet-4009
How about creating a new thread and make it as background to send data? Like below:

   Thread thread = new Thread(() =>
             {
                 while (true)
                 {
                     try
                     {
                        //your send data code 
                     }
                     catch (Exception ex) { MessageBox.Show(ex.ToString()); }
                 }
             });
             thread.IsBackground = true;
             thread.Start();
0 Votes 0 ·

0 Answers