While I was refactoring some old C# code for document generation with the Office.Interop
library, I found this and because of it was using UI context. When functions were called from it it was blocking it
For example:
private void btnFooClick(object sender, EventArgs e)
{
bool documentGenerated = chckBox.Checked ? updateDoc() : newDoc();
if(documentGenerated){
//do something
}
}
I decided to change it to reduce from blocking UI:
private async void btnFooClick(object sender, EventArgs e)
{
bool documentGenerated; = chckBox.Checked ? updateDoc() : newDoc();
if(chckBox.Checked)
{
documentGenerated = await Task.Run(() => updateDoc()).ConfigureAwait(false);
}
else
{
documentGenerated = await Task.Run(() => newDoc()).ConfigureAwait(false);
}
if(documentGenerated){
//do something
}
}
It was throwing this error:
Current thread must be set to single thread apartment (STA) mode
before OLE calls can be made
Why does it happen and what is the workaround?