I'm developing a VSTO Outlook add-in in VS2010. In the ThisAddIn_Startup
method (which is called when the addin starts) my code needs to check if Outlook is running on the company network or not. If Outlook isn't running on the network it takes about 3 seconds to come back with the answer. So I wrapped the code up in a Task to make it run Async to ensure it doesn't hang Outlook while it's checking.
e.g.
bool onNetwork = false;
Task task = Task.Factory.StartNew(() =>
{
onNetwork = IsConnectedToNetwork();
});
After it's finished checking it needs to load and display the relevant Form. So I changed the code to:
Task task = Task.Factory.StartNew(() =>
{
if (IsConnectedToNetwork())
{
OnNetworkForm onNetworkForm = new OnNetworkForm();
onNetworkForm.Show();
}
else
{
OffNetworkForm offNetworkForm = new OffNetworkForm();
offNetworkForm.Show();
}
});
But the Forms need to be loaded on the UI Thread. Otherwise I get an InvalidOptionationException
when it tries to load and show the forms with the message:
The calling thread must be STA, because many UI components require this.
My question is how can I make the forms load on the UI Thread?
Please note
I can't use await as that's C# 5.0 and VS 2010 doesn't support C# 5.0.
And the ThisAddin class isn't a control and therefore doesn't have the BeginInvoke
or Invoke
methods available.