【问题标题】:Updating bulk data freezes screen更新批量数据冻结屏幕
【发布时间】:2016-02-15 12:52:27
【问题描述】:

我正在尝试更新大量数据...当我单击更新按钮时屏幕冻结...我敢打赌它会等待过程完成...

没有错误:我想要的是类似jquery.promise() 的东西,我可以按顺序执行它们......但我仍然不知道C# 中是否有类似的代码......我也尝试过task.factory 但仍然无法理解这个想法......提前谢谢

//first execution
gvPriceListDetails.Visible = false;
lblLoading.BringToFront();
lblLoading.Visible = true;

//wait for the updateprocess to complete
if(_svc.UpdatePriceList(_model))
{
    UiHelpers.ShowSuccessForm("Price Lists Successfully Updated!");
    EditingMode(false);
    ShowDetails(_model.PricelistID);  
}


//execute when update process is complete
lblLoading.Visible = false;
gvPriceListDetails.Visible = true;

我正在使用C#,这是一个 Windows 窗体应用程序。

【问题讨论】:

    标签: c# async-await


    【解决方案1】:

    试试这个:

    var result = await Task.Run(() => UpdatePriceList(_model));
    

    【讨论】:

      【解决方案2】:

      您可以改用 BackgroundWorker。 (*您需要先声明并初始化后台工作人员 关注link

      应该是这样的

      //Upload process calling method
      private void Upload(_model)
      {
         //calling BG worker
         UploadBGWorker.RunWorkerAsync(new Arguments(_model))
      }
      
      UploadBGWorker_DoWorker(Arguments e)
      {
         Model _model = e.model;//first execution
         gvPriceListDetails.Visible = false;
         lblLoading.BringToFront();
         lblLoading.Visible = true;
      
      //wait for the updateprocess to complete
         if(_svc.UpdatePriceList(_model))
         {
            UiHelpers.ShowSuccessForm("Price Lists Successfully Updated!");
            e.Result = true;
         }
      }
      
      UploadBGWorker_RunWorkerCompleted(Arguments e)
      {
         if(e.Result != null && e.Result == true)
         {
            //execute on successful upload
            EditingMode(false);
            ShowDetails(_model.PricelistID);  
         }
         //execute when update process is complete
         lblLoading.Visible = false;
         gvPriceListDetails.Visible = true;
      }
      

      【讨论】:

        【解决方案3】:

        您看过下面由 Xelom 发布的链接吗?这对我来说有意义吗? 我希望这可以帮助你。谢谢,

        Save Records in Database asynchronously Or Parallely in .net c#

           public async List<SearchedItems> SearchItems(string ItemToSearch, string AuthenticationToken)
        {
        }
        

        然后就可以等待 saveToDb 任务了:

         var result = await Task.Factory.StartNew(()=> saveToDb(_list));
        

        【讨论】:

        • Don't use StartNew with async/await,请改用Task.Run(。如果您使用 StartNew 并且不传入 TaskScheduler,您最终可能会在 UI 线程上得到您希望在后台线程上的代码。
        • @ScottChamberlain 如果用户尝试关闭表单,是否可以取消update
        • 可能,您需要通过CancellationToken 编写支持它的代码。去learn about the subject,如果你看完那篇文章还是不明白怎么做,那就去问一个新问题。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-13
        • 2020-07-03
        相关资源
        最近更新 更多