When attempting to access my "searchResultCollection" property after modifying it in a separate thread (I've tried both background workers and just threads) I receive the below exception. The exception occurs whether I use the BackgroundWorker e.Result property or just set the classes property directly.
If I do all my processing in a single thread everything is fine.
Removing [STAThread] from my main function fixes the problem, but as I'm using windows forms isn't this bad practice?
What is the proper way to update a windows forms properties via a separate thread?
Exception:
System.InvalidCastException: 'Unable to cast COM object of type 'System.__ComObject' to interface type 'IDirectorySearch'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{109BA8EC-92F0-11D0-A790-00C04FD8D5A8}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).'
Form class:
public partial class ActiveDirectoryDiscovery : Form
{
private DirectorySearcher directorySearcher;
private SearchResultCollection searchResults;
private BackgroundWorker runSearchWorker;
public ActiveDirectoryDiscovery()
{
InitializeComponent();
}
private void button_Start_Click(object sender, EventArgs e)
{
runSearchWorker = new BackgroundWorker();
runSearchWorker.DoWork += RunSearchWorker_DoWork;
runSearchWorker.RunWorkerCompleted += RunSearchWorker_RunWorkerCompleted;
runSearchWorker.RunWorkerAsync();
}
private void RunSearchWorker_DoWork(object sender, DoWorkEventArgs e)
{
string filter = this.textBox_LDAPQuery.Text;
directorySearcher = new DirectorySearcher(filter);
this.searchResults = directorySearcher.FindAll();
}
private void RunSearchWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
foreach (SearchResult result in this.searchResults) {
if (!result.Properties["objectclass"].Contains("computer")) {
return;
}
else {
ListViewItem newItem = new ListViewItem((string)result.Properties["cn"][0]);
this.listView_SearchResults.Items.Add(newItem);
}
}
}
}
User contributions licensed under CC BY-SA 3.0