C# 在windows窗体应用程序中填充组合框的后台工作程序
我想在我的windows应用程序中实现后台工作程序。 目前,我正在使用按钮事件处理程序加载包含数据的组合框。由于查询挂起用户界面,我想实现后台工作程序,因为查询在不同的线程中运行。我从未在我的任何应用程序中使用过此后台工作程序。我对此做了一些研究,但仍然无法实现。任何帮助或建议都将不胜感激 这就是我的按钮事件处理程序的外观C# 在windows窗体应用程序中填充组合框的后台工作程序,c#,winforms,active-directory,backgroundworker,C#,Winforms,Active Directory,Backgroundworker,我想在我的windows应用程序中实现后台工作程序。 目前,我正在使用按钮事件处理程序加载包含数据的组合框。由于查询挂起用户界面,我想实现后台工作程序,因为查询在不同的线程中运行。我从未在我的任何应用程序中使用过此后台工作程序。我对此做了一些研究,但仍然无法实现。任何帮助或建议都将不胜感激 这就是我的按钮事件处理程序的外观 private void button6_Click(object sender, EventArgs e) { if (comboB
private void button6_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "All")
{
findAllUser();
}
else
{
//Do Something!!!
}
}
findAllUser()将从active directory中获取所有用户,这通常需要时间,并使UI无响应。findAllUser()的代码如下所示
public void findAllUser()
{
System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry("LDAP://DC=xyz, DC=com");
System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(entry);
mySearcher.Filter = "(&(objectClass=user))";
foreach (System.DirectoryServices.SearchResult resEnt in mySearcher.FindAll())
{
try
{
System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry();
comboBox2.Items.Add(de.Properties["GivenName"].Value.ToString() + " " + de.Properties["sn"].Value.ToString() + " " + "[" + de.Properties["sAMAccountName"].Value.ToString() + "]");
}
catch (Exception)
{
// MessageBox.Show(e.ToString());
}
}
}
Thread thread = new Thread(() =>
{
// do process here
});
thread.IsBackground = true;
thread.Start();
下面是后台工作人员现在的样子..全部为空
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
任何建议如何实现上述代码,以便后台工作人员使用active directory用户列表填充combobox2
将您的代码放在后台工作上。但我建议您使用线程或任务并行库 如果您使用的是.NET4.0,请使用TPL 您可以这样做:
Task runner = new Task(() =>
{
// do process here
});
runner.Start();
private List<string> items;
public void findAllUser()
{
items = new List<string>();
System.DirectoryServices.DirectoryEntry entry =
new System.DirectoryServices.DirectoryEntry("LDAP://DC=xyz, DC=com");
System.DirectoryServices.DirectorySearcher mySearcher =
new System.DirectoryServices.DirectorySearcher(entry);
mySearcher.Filter = "(&(objectClass=user))";
foreach (System.DirectoryServices.SearchResult resEnt in mySearcher.FindAll())
{
try
{
System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry();
items.Add(de.Properties["GivenName"].Value.ToString() + " " +
de.Properties["sn"].Value.ToString() + " " + "[" +
de.Properties["sAMAccountName"].Value.ToString() + "]");
}
catch (Exception)
{
// MessageBox.Show(e.ToString());
}
}
}
public void findAllUser()
{
const int ExpectedTime = 30000; // 30,000 milliseconds
// stopwatch keeps track of elapsed time
Stopwatch sw = Stopwatch.StartNew();
// Create a timer that reports progress at 500 ms intervals
System.Timers.Timer UpdateTimer;
UpdateTimer = new System.Threading.Timer(
null,
{
var percentComplete = (100 * sw.ElapsedMilliseconds) / ExpectedTime;
if (percentComplete > 100) percentComplete = 100;
ReportProgress(percentComplete);
// Update again in 500 ms if not already at max
if (percentComplete < 100)
UpdateTimer.Change(500, Timeout.Infinite);
}, 500, Timeout.Infinite);
items = new List<string>();
// rest of findAllUser here
// dispose of the timer.
UpdateTimer.Dispose();
}
当然,如果您使用的是较旧的框架,请像这样使用线程
public void findAllUser()
{
System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry("LDAP://DC=xyz, DC=com");
System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(entry);
mySearcher.Filter = "(&(objectClass=user))";
foreach (System.DirectoryServices.SearchResult resEnt in mySearcher.FindAll())
{
try
{
System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry();
comboBox2.Items.Add(de.Properties["GivenName"].Value.ToString() + " " + de.Properties["sn"].Value.ToString() + " " + "[" + de.Properties["sAMAccountName"].Value.ToString() + "]");
}
catch (Exception)
{
// MessageBox.Show(e.ToString());
}
}
}
Thread thread = new Thread(() =>
{
// do process here
});
thread.IsBackground = true;
thread.Start();
阅读有关和的更多信息。将您的代码放在backgroundWorker1\u DoWork上。但我建议您使用线程或任务并行库 如果您使用的是.NET4.0,请使用TPL 您可以这样做:
Task runner = new Task(() =>
{
// do process here
});
runner.Start();
private List<string> items;
public void findAllUser()
{
items = new List<string>();
System.DirectoryServices.DirectoryEntry entry =
new System.DirectoryServices.DirectoryEntry("LDAP://DC=xyz, DC=com");
System.DirectoryServices.DirectorySearcher mySearcher =
new System.DirectoryServices.DirectorySearcher(entry);
mySearcher.Filter = "(&(objectClass=user))";
foreach (System.DirectoryServices.SearchResult resEnt in mySearcher.FindAll())
{
try
{
System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry();
items.Add(de.Properties["GivenName"].Value.ToString() + " " +
de.Properties["sn"].Value.ToString() + " " + "[" +
de.Properties["sAMAccountName"].Value.ToString() + "]");
}
catch (Exception)
{
// MessageBox.Show(e.ToString());
}
}
}
public void findAllUser()
{
const int ExpectedTime = 30000; // 30,000 milliseconds
// stopwatch keeps track of elapsed time
Stopwatch sw = Stopwatch.StartNew();
// Create a timer that reports progress at 500 ms intervals
System.Timers.Timer UpdateTimer;
UpdateTimer = new System.Threading.Timer(
null,
{
var percentComplete = (100 * sw.ElapsedMilliseconds) / ExpectedTime;
if (percentComplete > 100) percentComplete = 100;
ReportProgress(percentComplete);
// Update again in 500 ms if not already at max
if (percentComplete < 100)
UpdateTimer.Change(500, Timeout.Infinite);
}, 500, Timeout.Infinite);
items = new List<string>();
// rest of findAllUser here
// dispose of the timer.
UpdateTimer.Dispose();
}
当然,如果您使用的是较旧的框架,请像这样使用线程
public void findAllUser()
{
System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry("LDAP://DC=xyz, DC=com");
System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(entry);
mySearcher.Filter = "(&(objectClass=user))";
foreach (System.DirectoryServices.SearchResult resEnt in mySearcher.FindAll())
{
try
{
System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry();
comboBox2.Items.Add(de.Properties["GivenName"].Value.ToString() + " " + de.Properties["sn"].Value.ToString() + " " + "[" + de.Properties["sAMAccountName"].Value.ToString() + "]");
}
catch (Exception)
{
// MessageBox.Show(e.ToString());
}
}
}
Thread thread = new Thread(() =>
{
// do process here
});
thread.IsBackground = true;
thread.Start();
阅读有关和的更多信息。您可以使用以下逻辑为代码实现后台工作程序
var startListenerWorker = new BackgroundWorker();
startListenerWorker.DoWork += new DoWorkEventHandler(this.StartListenerDoWork);
startListenerWorker.RunWorkerAsync();
private void StartListenerDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
// Your logic to load comboBox will go here for running your query
}
您还可以实现线程,使逻辑在单独的线程上运行。您可以使用下面的逻辑为代码实现后台工作程序
var startListenerWorker = new BackgroundWorker();
startListenerWorker.DoWork += new DoWorkEventHandler(this.StartListenerDoWork);
startListenerWorker.RunWorkerAsync();
private void StartListenerDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
// Your logic to load comboBox will go here for running your query
}
您还可以实现线程,使逻辑在单独的线程上运行。使用BackgroundWorker很方便,因为它自动调用UI线程中的ProgressChanged和RunworkerCompleted事件处理程序。你可以像下面那样使用它
private void AddItem(DirectoryEntry de)
{
comboBox2.Items.Add(de.Properties["GivenName"].Value.ToString() + " " + de.Properties["sn"].Value.ToString() + " " + "[" + de.Properties["sAMAccountName"].Value.ToString() + "]");
}
private void button6_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "All")
{
this.backgroundWorker1.RunWorkerAsync();
}
else
{
//Do Something!!!
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Bind to the users container.
DirectoryEntry entry = new DirectoryEntry("LDAP://CN=xyz,DC=com");
// Create a DirectorySearcher object.
DirectorySearcher mySearcher = new DirectorySearcher(entry);
try
{
// Create a SearchResultCollection object to hold a collection of SearchResults
// returned by the FindAll method.
SearchResultCollection result = mySearcher.FindAll();
int count = result.Count;
for(int i = 0; i < count; i++)
{
SearchResult resEnt = result[i];
try
{
DirectoryEntry de = resEnt.GetDirectoryEntry();
BeginInvoke(new Action<DirectoryEntry>(AddItem), de);
}
catch (Exception)
{
// MessageBox.Show(e.ToString());
}
this.backgroundWorker1.ReportProgress(i / count);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.progressBar1.Value = 100;
}
private void AddItem(目录条目de)
{
comboBox2.Items.Add(de.Properties[“GivenName”].Value.ToString()+“”+de.Properties[“sn”].Value.ToString()+“”+“[”+de.Properties[“sAMAccountName”].Value.ToString()+“]”);
}
私有无效按钮6_单击(对象发送者,事件参数e)
{
如果(comboBox1.SelectedItem.ToString()=“全部”)
{
this.backgroundWorker1.RunWorkerAsync();
}
其他的
{
//做点什么!!!
}
}
私有void backgroundWorker1\u DoWork(对象发送方,DoWorkEventArgs e)
{
//绑定到用户容器。
DirectoryEntry=新的DirectoryEntry(“LDAP://CN=xyz,DC=com”);
//创建DirectorySearcher对象。
DirectorySearcher mySearcher=新的DirectorySearcher(条目);
尝试
{
//创建SearchResultCollection对象以保存SearchResults集合
//由FindAll方法返回。
SearchResultCollection result=mySearcher.FindAll();
int count=result.count;
for(int i=0;i
使用BackgroundWorker很方便,因为它自动调用UI线程中的ProgressChanged和RunworkerCompleted事件处理程序。你可以像下面那样使用它
private void AddItem(DirectoryEntry de)
{
comboBox2.Items.Add(de.Properties["GivenName"].Value.ToString() + " " + de.Properties["sn"].Value.ToString() + " " + "[" + de.Properties["sAMAccountName"].Value.ToString() + "]");
}
private void button6_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "All")
{
this.backgroundWorker1.RunWorkerAsync();
}
else
{
//Do Something!!!
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Bind to the users container.
DirectoryEntry entry = new DirectoryEntry("LDAP://CN=xyz,DC=com");
// Create a DirectorySearcher object.
DirectorySearcher mySearcher = new DirectorySearcher(entry);
try
{
// Create a SearchResultCollection object to hold a collection of SearchResults
// returned by the FindAll method.
SearchResultCollection result = mySearcher.FindAll();
int count = result.Count;
for(int i = 0; i < count; i++)
{
SearchResult resEnt = result[i];
try
{
DirectoryEntry de = resEnt.GetDirectoryEntry();
BeginInvoke(new Action<DirectoryEntry>(AddItem), de);
}
catch (Exception)
{
// MessageBox.Show(e.ToString());
}
this.backgroundWorker1.ReportProgress(i / count);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.progressBar1.Value = 100;
}
private void AddItem(目录条目de)
{
comboBox2.Items.Add(de.Properties[“GivenName”].Value.ToString()+“”+de.Properties[“sn”].Value.ToString()+“”+“[”+de.Properties[“sAMAccountName”].Value.ToString()+“]”);
}
私有无效按钮6_单击(对象发送者,事件参数e)
{
如果(comboBox1.SelectedItem.ToString()=“全部”)
{
this.backgroundWorker1.RunWorkerAsync();
}
其他的
{
//做点什么!!!
}
}
私有void backgroundWorker1\u DoWork(对象发送方,DoWorkEventArgs e)
{
//绑定到用户容器。
DirectoryEntry=新的DirectoryEntry(“LDAP://CN=xyz,DC=com”);
//创建DirectorySearcher对象。
DirectorySearcher mySearcher=新的DirectorySearcher(条目);
尝试
{
//创建SearchResultCollection对象以保存SearchResults集合
//由FindAll方法返回。
SearchResultCollection result=mySearcher.FindAll();
int count=result.count;
for(int i=0;i