C# WPF:添加项目需要时间

C# WPF: add item taking time

我正在尝试将安全组从服务器添加到后台工作程序中的组合框。 但这需要时间,尽管有后台工作人员 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 的情况下创建一个集合。当您循环 results.

时,实际的 AD 流量就完成了

所以请尝试在 bgw_account_DoWork 中循环 results 并将生成的 samAccountNames 放入列表中以供在 bgw_account_RunWorkerCompleted.

中使用