async ForEach for a big collection

时间:2015-06-01 07:54:47

标签: c# asynchronous collections windows-phone

此集合包含大约500或1000个元素。在某些情况下,有几个集合。在UI线程中,它的工作速度非常慢。我正在制作Silverlight应用程序,其中异步只是让应用程序快速运行的方法。我采取了非常简单的方法(使用任何异步操作或Task.Run()方法)。这是第一种方法的例子:

foreach (SpecialSongs.SongJSON futuresongs in pop)
{
    SpecialSongs.SongJSON sooong = new SpecialSongs.SongJSON();
    sooong.Artist = futuresongs.Artist;
    sooong.Duration = futuresongs.Duration;
    sooong.URI = futuresongs.URI;
    sooong.Title = futuresongs.Title;
    sooong.OwnerId = futuresongs.OwnerId;
    sooong.Id = futuresongs.Id;
    SpecialSongs.SongJSON songstocoll = new SpecialSongs.SongJSON();
    songstocoll.Artist = futuresongs.Artist;
    songstocoll.Duration = futuresongs.Duration;
    songstocoll.GenreId = futuresongs.GenreId;
    songstocoll.Id = futuresongs.Id;
    songstocoll.LyricsId = futuresongs.LyricsId;
    songstocoll.OwnerId = futuresongs.OwnerId;
    songstocoll.Title = futuresongs.Title;
    songstocoll.URI = futuresongs.URI;
    songstocoll.Song = sooong;
    popBindList.Add(songstocoll);
}
PopLongList.ItemsSource = popBindList;
PopText.Visibility = System.Windows.Visibility.Collapsed;

第二种方法:(小异步)

RockLongList.ItemsSource = await Task<List<SpecialSongs.SongJSON>>.Run(() =>
{
    List<SpecialSongs.SongJSON> callback = new List<SpecialSongs.SongJSON>();
    foreach (SpecialSongs.SongJSON futuresongs in rock)
    {
        SpecialSongs.SongJSON sooong = new SpecialSongs.SongJSON();
        sooong.Artist = futuresongs.Artist;
        sooong.Duration = futuresongs.Duration;
        sooong.URI = futuresongs.URI;
        sooong.Title = futuresongs.Title;
        sooong.OwnerId = futuresongs.OwnerId;
        sooong.Id = futuresongs.Id;
        SpecialSongs.SongJSON songstocoll = new SpecialSongs.SongJSON();
        songstocoll.Artist = futuresongs.Artist;
        songstocoll.Duration = futuresongs.Duration;
        songstocoll.GenreId = futuresongs.GenreId;
        songstocoll.Id = futuresongs.Id;
        songstocoll.LyricsId = futuresongs.LyricsId;
        songstocoll.OwnerId = futuresongs.OwnerId;
        songstocoll.Title = futuresongs.Title;
        songstocoll.URI = futuresongs.URI;
        songstocoll.Song = sooong;
        callback.Add(songstocoll);
    }
    return callback;
});
RockText.Visibility = System.Windows.Visibility.Collapsed;

我是使用异步制作循环的新手。我找到了这个例子:http://blogs.msdn.com/b/pfxteam/archive/2012/03/04/10277325.aspx ,但我不知道如何使用。谢谢,对不起我的英语和正规化。我希望你的决定能解决我的问题。

0 个答案:

没有答案