c# – .Net:后台工作者和多个CPU
发布时间:2020-12-16 00:01:39 所属栏目:百科 来源:网络整理
导读:我正在使用BackgroundWorker在后台执行一些繁重的操作,以便UI不会无响应. 但今天我注意到,当我运行程序时,只使用了两个CPU中的一个. 有没有办法将所有CPU与BackgroundWorker一起使用? 这是我的简化代码,就好像你很好奇! private System.ComponentModel.Bac
我正在使用BackgroundWorker在后台执行一些繁重的操作,以便UI不会无响应.
但今天我注意到,当我运行程序时,只使用了两个CPU中的一个. 有没有办法将所有CPU与BackgroundWorker一起使用? 这是我的简化代码,就好像你很好奇! private System.ComponentModel.BackgroundWorker bwPatchApplier; this.bwPatchApplier.WorkerReportsProgress = true; this.bwPatchApplier.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bwPatchApplier_DoWork); this.bwPatchApplier.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.bwPatchApplier_ProgressChanged); this.bwPatchApplier.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bwPatchApplier_RunWorkerCompleted); private void bwPatchApplier_DoWork(object sender,DoWorkEventArgs e) { string pc1WorkflowName; string pc2WorkflowName; if (!GetWorkflowSettings(out pc1WorkflowName,out pc2WorkflowName)) return; int progressPercentage = 0; var weWorkspaces = (List<WEWorkspace>) e.Argument; foreach (WEWorkspace weWorkspace in weWorkspaces) { using (var spSite = new SPSite(weWorkspace.SiteId)) { foreach (SPWeb web in spSite.AllWebs) { using (SPWeb spWeb = spSite.OpenWeb(web.ID)) { PrintHeader(spWeb.ID,spWeb.Title,spWeb.Url,bwPatchApplier); try { for (int index = 0; index < spWeb.Lists.Count; index++) { SPList spList = spWeb.Lists[index]; if (spList.Hidden) continue; string listName = spList.Title; if (listName.Equals("PC1") || listName.Equals("PC2")) { #region STEP 1 // STEP 1: Remove Workflow #endregion #region STEP 2 // STEP 2: Add Events: Adding & Updating #endregion } if ((uint) spList.BaseTemplate == 10135 || (uint) spList.BaseTemplate == 10134) { #region STEP 3 // STEP 3: Configure Custom AssignedToEmail Property #endregion #region STEP 4 if (enableAssignToEmail) { // STEP 4: Install AssignedTo events to Work lists } #endregion } #region STEP 5 // STEP 5 Install Notification Events #endregion #region STEP 6 // STEP 6 Install Report List Events #endregion progressPercentage += TotalSteps; UpdatePercentage(progressPercentage,bwPatchApplier); } } catch (Exception exception) { progressPercentage += TotalSteps; UpdatePercentage(progressPercentage,bwPatchApplier); } } } } } PrintMessage(string.Empty,bwPatchApplier); PrintMessage("*** Process Completed",bwPatchApplier); UpdateStatus("Process Completed",bwPatchApplier); } 非常感谢您对此进行调查:) 解决方法
BackgroundWorker在单个后台(ThreadPool)线程中完成工作.因此,如果计算量很大,它将大量使用一个CPU. UI线程仍然在第二个运行,但可能(像大多数用户界面工作一样)花费几乎所有的时间空闲等待输入(这是一件好事).
如果要将工作拆分为使用多个CPU,则需要使用其他一些技术.这可以是多个BackgroundWorker组件,每个组件都可以完成一些工作,也可以直接使用ThreadPool.通过TPL在.NET 4中简化了并行编程,这可能是一个非常好的选择.有关详细信息,请参阅my series on the TPL或MSDN’s page on the Task Parallel Library. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |