locked
Task action error RRS feed

  • Question

  • Here is my code

    Action<object> action = (object obj) =>// update currency
                {
                    prLoading.Visibility = Visibility.Collapsed;
    
                };
    
                Task ct = new Task(action, "UpdateData");
                ct.Start();

    The prLoading is a ProgressRing, when I debug the code it's always popup error: "The application called an interface that was marshalled for a different thread." in line "prLoading.Visibility = Visibility.Collapsed;"

    It seems it's not allowed to operate in different thread.

    Is there any other way to solve this issue, I just want when app updating data, the ProgressRing could be appear.

    Thanks

    Tuesday, May 20, 2014 1:39 PM

Answers

  • You must only access UI elements on the UI thread so you need to use the Dispatcher here:

    Action<object> action = async (object obj) =>// update currency
                {
                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                            () =>
                            {
                                prLoading.Visibility = Visibility.Collapsed;
                            });
    
                };
    
                Task ct = new Task(action, "UpdateData");
                ct.Start();


    • Edited by Magnus (MM8)MVP Tuesday, May 20, 2014 9:12 PM
    • Proposed as answer by Dave SmitsMVP Wednesday, May 21, 2014 10:09 AM
    • Marked as answer by Anne Jing Thursday, May 29, 2014 3:39 AM
    Tuesday, May 20, 2014 9:12 PM

All replies

  • You must only access UI elements on the UI thread so you need to use the Dispatcher here:

    Action<object> action = async (object obj) =>// update currency
                {
                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                            () =>
                            {
                                prLoading.Visibility = Visibility.Collapsed;
                            });
    
                };
    
                Task ct = new Task(action, "UpdateData");
                ct.Start();


    • Edited by Magnus (MM8)MVP Tuesday, May 20, 2014 9:12 PM
    • Proposed as answer by Dave SmitsMVP Wednesday, May 21, 2014 10:09 AM
    • Marked as answer by Anne Jing Thursday, May 29, 2014 3:39 AM
    Tuesday, May 20, 2014 9:12 PM
  • Awesome, thanks.
    Wednesday, May 21, 2014 1:41 PM