多线程与Windows商店应用程序

本文关键字:应用程序 Windows 多线程 | 更新日期: 2023-09-27 18:17:19

我们目前正在创建一个Windows Store应用程序,它从RSS提要获取信息并将这些信息输入到ObservableCollection中。我们遇到的问题是,当获取信息时,应用程序UI变得无响应。

为了解决这个问题,我考虑创建一个新线程并在其中调用该方法。然而,经过一番研究,我们意识到这在Windows Store应用程序中不再可能了。我们怎么才能避开这个问题呢?

收集信息的方法如下。

public void getFeed()
{
    setupImages();
    string[] feedUrls = new string[] {
        "http://www.igadgetos.co.uk/blog/category/gadget-news/feed/",
        "http://www.igadgetos.co.uk/blog/category/gadget-reviews/feed/",
        "http://www.igadgetos.co.uk/blog/category/videos/feed/",
        "http://www.igadgetos.co.uk/blog/category/gaming/feed/",
        "http://www.igadgetos.co.uk/blog/category/jailbreak-2/feed/",
        "http://www.igadgetos.co.uk/blog/category/kickstarter/feed/",
        "http://www.igadgetos.co.uk/blog/category/cars-2/feed/",
        "http://www.igadgetos.co.uk/blog/category/software/feed/",
        "http://www.igadgetos.co.uk/blog/category/updates/feed/"
    };
    {
        try
        {
            XNamespace dc = "http://purl.org/dc/elements/1.1/";
            XNamespace content = "http://purl.org/rss/1.0/modules/content/";
            foreach (var feedUrl in feedUrls)
            {
                var doc = XDocument.Load(feedUrl);
                var feed = doc.Descendants("item").Select(c => new ArticleItem() //Creates a copy of the ArticleItem Class.
                {
                    Title = c.Element("title").Value,
                    //There are another 4 of these.
                    Post = stripTags(c.Element(content + "encoded").Value)                        }
                ).OrderByDescending(c => c.PubDate);
                this.moveItems = feed.ToList();
                foreach (var item in moveItems)
                {
                    item.ID = feedItems.Count;
                    feedItems.Add(item);
                }
            }
            lastUpdated = DateTime.Now;
        }
        catch
        {
            MessageDialog popup = new MessageDialog("An error has occured downloading the feed, please try again later.");
            popup.Commands.Add(new UICommand("Okay"));
            popup.Title = "ERROR";
            popup.ShowAsync();
        }
    }
}

当我们获得这些信息时,我们如何能够使应用程序不冻结,因为线程在Windows Store应用程序中是不可能的。

E。g -我们计划使用;

Thread newThread = new Thread(getFeed);
newThread.Start

多线程与Windows商店应用程序

对于发生在UI线程上的操作,您需要使用文档完备的异步模式。Paul-Jan在评论中给出的链接是你需要开始的地方。http://msdn.microsoft.com/en-us/library/windows/apps/hh994635.aspx