c# - Passing collection from backgroundworker DoWork to backgroundworker Completed and perform a foreach -
my goal here is:
- user types full or partial computername combobox
- button click event starts background worker passing computername dowork method
- dowork method searches activedirectory computername , passes collection workercompleted method
- workercompleted method adds each computername combobox items.
my error @ foreach loop in backgroundworker_runworkercompleted method.
- "foreach statement cannot operate on variables of type 'object' because 'object' not contain public definition 'getenumerator'"
if messagebox.show(results.first().tostring()); in dowork method, can view first computername in collection. (forgive me if collection correct term)
if messagebox.show(e.result.tostring()); in dowork , workercompleted method, this:
- "system.directoryservices.accountmanagement.principalsearchresult`1[system.directoryservices.accountmanagement.principal]"
i picked c# month ago , i'm coming powershell apologize in advance if i'm using wrong vocabulary. new me.
any guidance on appreciated!
private void button1_click(object sender, eventargs e) { //saves computername entered user pass dowork method string pcname = combobox1.text; //start background thread passing computer dowork method backgroundworker1.runworkerasync(pcname); } private void backgroundworker1_dowork(object sender, doworkeventargs e) { using (principalcontext ctx = new principalcontext(contexttype.domain)) { //setup filter computerprincipal computer = new computerprincipal(ctx); computer.name = "*" + e.argument + "*"; //search pc principalsearcher ps = new principalsearcher(); ps.queryfilter = computer; //get results principalsearchresult<principal> results = ps.findall(); //results passed runworkercompleted e.result = results; } } private void backgroundworker1_runworkercompleted(object sender, runworkercompletedeventargs e) { //add each computername combobox foreach (object pc in e.result) // <--------------- error here! { combobox1.items.add(pc.tostring()); } } }
you have cast e.result
in completed handler object
principalsearchresult<principal>
in order iterate through it.
private void backgroundworker1_runworkercompleted(object sender, runworkercompletedeventargs e) { //add each computername combobox principalsearchresult<principal> results = (principalsearchresult<principal>)e.result; foreach (principal pc in results) { combobox1.items.add(pc.tostring()); } }
edit:
principalsearcher
can't used in background worker, because it's uses of com component requires single-threaded apartment (sta). background worker thread runs in multithreaded apartment (mta). apartmentstate can set using thread.setapartmentstate
, must called before thread starts (so can't used change apartmentstate of backgroundworker's working thread).
Comments
Post a Comment