在Async方法中创建Xaml元素

时间:2014-07-01 00:40:43

标签: xaml asynchronous windows-store-apps

我有一个方法从sqlite数据库中获取数据,并根据数据创建了一些xaml元素,这种方法是一种繁重的方法。我试图异步执行它,但它给了我这个例外:

The application called an interface that was marshalled for a different thread 

   at Windows.UI.Xaml.Controls.StackPanel..ctor()
   at Helper.DrawPage.InitPage()
   at Helper.PageProvider.GetPage(Int32 chapterIndex, Int32 pageIndex)
   at WinRT.View.Main.loadPages()
   at WinRT.View.Main.<TurnPageNext_Completed>b__0()
   at System.Threading.Tasks.Task.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()

我的代码:

        public void loadPages()
        {

            PageProvider pageProvider = new PageProvider();
            pageProvider.SetPageSize(new Size(400, 564));
            FrameworkElement fm =  pageProvider.GetPage(0, (currentPage + 2));
            fm.Name = "c_" + ((currentPage + 2) + 1);
            Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => pageContent.Add(fm));
}

感谢

//animation completed event
async void TurnPageNext_Completed(object sender, object e)
        {
 await Task.Run(() => loadPages());
}

2 个答案:

答案 0 :(得分:1)

FrameworkElements也需要在调度程序线程上创建,因此您的pageProvider.GetPage()调用可能会在后台线程上运行并抛出。您可以尝试启用中断第一次机会异常(Ctrl + Alt + E,检查所有适用的)以查看最初发生异常的位置。

答案 1 :(得分:1)

Task.Run启动一个新线程来创建页面,然后使用Dispatcher.RunAsync将FrameworkElement添加回UI线程。这就是你得到错误的原因,FrameworkElement fm来自不同的线程。

在UI线程异步中创建FrameworkElement fm,如下所示:

Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,()=>{
    PageProvider pageProvider = new PageProvider();
    pageProvider.SetPageSize(new Size(400, 564));
    FrameworkElement fm =  pageProvider.GetPage(0, (currentPage + 2));
    fm.Name = "c_" + ((currentPage + 2) + 1);
    pageContent.Add(fm)
});