c# WPF:添加项目占用时间
本文关键字:时间 项目 添加 WPF | 更新日期: 2023-09-27 18:12:16
我试图将安全组从服务器添加到后台工作人员的组合框。但这需要时间,尽管有后台工作UI变得无响应。
private void Accounts_Click(object sender, RoutedEventArgs e)
{
if (servername.Text == "")
MessageBox.Show("please enter server");
else
{
mycombobox.Items.Clear();
server1 = servername.Text;
bgw_account = new BackgroundWorker();
bgw_account.WorkerReportsProgress = true;
bgw_account.ProgressChanged += new ProgressChangedEventHandler(bgw_account_ProgressChanged);
bgw_account.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_account_RunWorkerCompleted);
bgw_account.DoWork += new DoWorkEventHandler(bgw_account_DoWork);
bgw_account.RunWorkerAsync();
}
}
private void bgw_account_DoWork(object sender, DoWorkEventArgs e)
{
ParallelOptions po = new ParallelOptions();
po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;
acclist = new List<string>();
using(PrincipalContext pt= new PrincipalContext(ContextType.Machine,server1.ToString()))
using (GroupPrincipal ab = new GroupPrincipal(pt))
using (var searcher=new PrincipalSearcher(ab))
using (var results=searcher.FindAll())
{
Parallel.ForEach(results,po,(currentsam)=>
{
acclist.Add(currentsam.SamAccountName.ToString());//timeconsuming task
});
}
}
private void bgw_account_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
mycombobox.Dispatcher.Invoke(new Action(() =>
{
mycombobox.Items.Clear();
}));
foreach (string p in acclist)
{
mycombobox.Dispatcher.Invoke( new Action (()=>
{
mycombobox.Items.Add(p);
}));
}
acclist.Clear();
}
有办法提高性能吗?
未测试
insPrincipalSearcher.FindAll()
所做的可能是创建一个集合而不实际搜索AD。实际的AD流量是在循环results
时完成的。
所以请尝试在bgw_account_DoWork
内循环results
,并将结果samAccountNames放在bgw_account_RunWorkerCompleted
中消费的列表中。