I have an application which loads email-addresses into a list and uses these for autocompletion in a textbox. If I close my application while these addresses are still being retrieved I get the InvalidComObjectException was unhandled by user code error.
The error is specified on a certain piece of code:
Outlook.NameSpace oNS = ((Microsoft.Office.Interop.Outlook.Application)OutlookObj).GetNamespace("MAPI");
This is the entire auto-completion class:
class AutoComplete
{
List<string> emailList = new List<string>();
Outlook.Application OutlookObj = new Outlook.Application();
string[] names;
public List<string> getEmails()
{
Outlook.AddressLists addresslists = OutlookObj.Session.AddressLists;
Outlook.AddressList gal = addresslists["All Users"];
Outlook.AddressEntries addrEntries = gal.AddressEntries;
names = new string[addrEntries.Count];
for (int i = 1; i < addrEntries.Count; i++)
{
Outlook.AddressEntry exchDLMember = addrEntries[i];
Outlook.NameSpace oNS = ((Microsoft.Office.Interop.Outlook.Application)OutlookObj).GetNamespace("MAPI");
Outlook.Recipient recip = oNS.CreateRecipient(exchDLMember.Name);
recip.Resolve();
if (recip.Address != null && recip.AddressEntry != null)
{
if (recip.AddressEntry.GetExchangeUser().PrimarySmtpAddress != null)
{
names[i] = recip.AddressEntry.GetExchangeUser().PrimarySmtpAddress;
}
}
}
foreach (string combo in names)
{
if (combo != null)
{
emailList.Add(combo);
}
else { }
}
return emailList;
}
}
The backgroundWorker methods in the Form:
void Form1_Shown(object sender, EventArgs e)
{
bgW.RunWorkerAsync();
bgW.WorkerSupportsCancellation = true;
}
void bgW_DoWork(object sender, DoWorkEventArgs e)
{
bgW.WorkerSupportsCancellation = true;
if(textBox1.InvokeRequired)
{
emails = autoComplete.getEmails();
collection.AddRange(emails.ToArray());
textBox1.Invoke(new MethodInvoker(delegate { textBox1.AutoCompleteCustomSource = collection; }));
}
for (int i = 100; i <= 100; i++)
{
bgW.ReportProgress(i);
if (i == 100)
{
label2.Invoke(new MethodInvoker(delegate { label2.Text = "Global Address List Loaded!"; }));
label2.Invoke(new MethodInvoker(delegate { label2.BackColor = System.Drawing.Color.LightGreen; }));
}
}
}
And upon closing the form:
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
bgW.CancelAsync();
}
Anyone have an idea about preventing this error?