我正在使用 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。 .NET 4 中通过 TPL 简化了并行编程,这可能是一个很好的选择。详情可以看my series on the TPL或 MSDN's page on the Task Parallel Library .
关于c# - .Net:后台 worker 和多 CPU,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8423834/