I have been reading a lot of stuff and I think I understand whats going on but I don't know how to fix it.
I have a c# wpf app. the user clicks a button and I start up another thread to do a lot of work. part of that is to open excel, create an excel file and do a lot of things to the excel sheet to set it up.
after that part is done the user will then use the app and there are some button to further interact with the excel file, like adding in more content.
My problem is I'm losing that COM object to the excel file when the thread completes. not sure how to fix this. here is my code (in late binding to excel)
..I have a public static class to contain on excel object
public static class MyGlobals
{
public static string ExcelprogID = "Excel.Application";
public static dynamic xlWorkBook;
public static dynamic xlApp;
}
..then the use clicks a button and I kick off another thread
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
string dialogValues = "...";//replaced code for simplicity
Thread t = new Thread(() => workerthread(dialogValues));
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
..then in the new thread I do a lot but one of the things is creating the excel object and setting that excel sheet up.
private void workerthread(string e)
{
MyGlobals.xlApp = Activator.CreateInstance(Type.GetTypeFromProgID(MyGlobals.ExcelprogID));
MyGlobals.xlWorkBook = MyGlobals.xlApp.Workbooks.Add(MyGlobals.misValue);
MyGlobals.xlApp.Visible = true;
//more code here to do stuff with excel.
}
...here is where my problem happens. now back on the main UI thread the user can click buttons to manipulate the stuff in the excel file. but I get this error
private void btnPlaceBM_Click(object sender, RoutedEventArgs e)
{
//Excel.Worksheet BM;
dynamic BM;
try
{
BM = MyGlobals.xlWorkBook.Sheets["CADD Basemaps"];
}
catch
{
MessageBox.Show("Project Index Excel file was closed! Can not place any data to excel file!");
return;
}
}
here is the error I get
System.Runtime.InteropServices.InvalidComObjectException was caught: "COM object that has been separated from its underlying RCW cannot be used."
Could someone give me some help..can I reget that excel object somehow??