nwein
Posts: 577
Joined: 2011-03-28
|
I've been struggling with this for a while now. I'm trying to run some async operations on my ADXOlForm task pane and change some controls once the the async operation finishes but I keep getting a Cross-thread operation not valid error. Now, usually I know the reason behind it, but in this case it shouldn't happen.
Consider the following code in a task pane with a single button on it:
private void button1_Click(object sender, EventArgs e)
{
DoSomething();
}
private async void DoSomething()
{
bool result = await AnAwaitableMethod();
button1.Text = DateTime.Now.ToString("T");
}
private async Task<bool> AnAwaitableMethod()
{
await Task.Run(() =>
{
for (int i = 1; i < 5; i++)
{
Thread.Sleep(1000);
}
});
return true;
}
In a regular winform this code would work just fine. The thread will switch when doing the awaitableMethod but will get back to the main thread after the bool result = await AnAwaitableMethod(); line.
In ADXOLForm that's not the case.
I can't even try to switch the thread context manually if I want.
Any help?
ADX 7.74087, Outlook 2010 32-bit, VS 2013 .NET 4.5.2 |
|
Dmitry Kostochko
Add-in Express team
Posts: 2887
Joined: 2004-04-05
|
|
nwein
Posts: 577
Joined: 2011-03-28
|
Thanks Dmitry, I'm familiar with the SendMessage approach and would probably use it, but i'm still intrigued as to why would that still be necessary in an ADXOlForm; this is not using the Outlook object module or even anything COM-related. I can see somewhat understand it if I was trying to manipulate my Outlook objects or anything of that sort, but that's not the case here. |
|
Dmitry Kostochko
Add-in Express team
Posts: 2887
Joined: 2004-04-05
|
Hello Nir,
Switching between thread contexts works fine in pure .NET applications. COM add-ins are located in a Win32 application (Outlook, Excel, etc.) and, as you can see, the code cannot get back to the main thread after executing an async method. |
|