(Windows 10, UWP, C#, XAML) I'm trying to change a rectangle's Fill from a class that is not the main method. I've sent my rectangle to the other class and from there I can set it's Fill. However, I need the Fill to change during an ongoing asynchronous method (rather, during a method that is being called by an on-going asynchronous method) but when I try that, I get an exception about threading:
The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
So, I've read about using Dispatcher to solve this sort of problem. It works for me ONLY when I don't leave the MainPage:
public async void printer()
{
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
Debug.WriteLine("I'm inside the printer before");
this.staffImageBorder.Fill = new SolidColorBrush(Colors.Blue);
Debug.WriteLine("I'm inside the printer after");
});
}
However, when I call this printer() method from my other class, it just skips right over the Fill change. Both Debug statements print.
I tried to move the Dispatcher code over to my other class but that class doesn't know what "Dispatcher" is (and neither do I ...).
Sorry I couldn't provide more code, I'm having difficulty replicating it on a simpler example. Any help would be greatly appreciated!
Dispatcher essentially manages dispatching events on the UI thread (and any updates to the UI need to be done on the UI thread!).
If you want to access it from outside a page you can access it via Window.Current.Dispatcher (or assign it as a static variable somewhere if you can't access Window - there's only ONE dispatcher per UI thread / Window that everything in that Window shares)
If it's printing both Debug statements however it's more than likely NOT skipping over your code, but you've got some issue elsewhere.
BTW, you probably want to re-write as a Task and NOT as an async void.
public Task SetPrintFillAsync()
{
return this.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
{
Debug.WriteLine("I'm inside the printer before");
this.staffImageBorder.Fill = new SolidColorBrush(Colors.Blue);
Debug.WriteLine("I'm inside the printer after");
});
}
And call like
await SetPrintFillAsync()
User contributions licensed under CC BY-SA 3.0