首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C# -如何不使WPF用户界面冻结,同时详细说明

C# -如何不使WPF用户界面冻结,同时详细说明
EN

Stack Overflow用户
提问于 2021-06-24 09:57:13
回答 1查看 145关注 0票数 0

我有一个按钮,点击它后,会在一个带有循环的远程数据库中发送大量数据,但是在这个操作期间,整个wpf UI都被冻结了。我的目标是使加载程序在处理数据库中的所有内容时工作。我的按钮代码:

代码语言:javascript
运行
复制
 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
        }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-24 10:09:17

在事件处理程序中运行后台操作的一种直接方法是声明事件处理程序async并运行并await为任务:

代码语言:javascript
运行
复制
private async void btn_Start_Click(object sender, RoutedEventArgs e)
{
     // prevent click while operation in progress
     btn_Start.IsEnabled = false;

     pb_loader.IsIndeterminate = true;

     // access UI elements before running the Task
     var mail = txtMail.Text + idIniziale + "@mail.local";
     ...

     await Task.Run(() =>
     {
         // perform background operation
         // use local variables "mail" etc. here
     });

     pb_loader.IsIndeterminate = false;

     btn_Start.IsEnabled = true;
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68113546

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档