制作方法异步

时间:2014-08-02 14:13:51

标签: c# windows-phone-8 asynchronous windows-phone async-await

我有一个方法可以列出媒体库中的所有歌曲。该方法有两个方面,它从SongsCollection返回MediaLibrary或返回自定义对象列表。

public static Task<object> GetSongList(bool lib = true, bool albumArt = true)
{
     MediaLibrary mediaLib = new MediaLibrary();
     var songs = mediaLib.Songs;

     if (lib)
     {
          return songs;
     }
     else
     {
          var list = new List<MusicTitle>();
          foreach (var song in songs)
          {
               list.Add(new MusicTitle()
               {
                   Artist = song.Artist.Name,
                   Title = song.Name,
                   Duration = (new DateTime(song.Duration.Ticks)).ToString("mm:ss"),
                   Album = song.Album.Name, 
                   Art = albumArt ? GetAlbumArt(song, 100) : null
               });
          }

          return list;
      }
  }

MusicTitle是具有一些属性的自定义类。因为这返回2种类型的结果我将返回类型设置为对象并适当地转换结果。这样可以保留UI,所以我需要async。因此,方法显示我将Task<object>添加到方法签名中,当我这样做时return songs;return lists;在编译错误后给出编译。

Cannot implicitly convert type 'Microsoft.Xna.Framework.Media.SongCollection' to 'System.Threading.Tasks.Task<object>'

Cannot implicitly convert type 'System.Collections.Generic.List<KVKWindowsPhoneHelper.Core.MediaLibrary.MusicTitle>' to 'System.Threading.Tasks.Task<object>'

我该怎么办?我尝试将返回类型转换为object但是没有用。我该如何制作这种方法async

修改

以下代码位于Page的OnNavigatedTo()方法旁边这会抛出UnauthorizedAccessException

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    // Set Song List
    List<AlphaKeyGroup<MusicTitle>> songList = await Task.Run(() => AlphaKeyGroup<MusicTitle>.CreateGroups(ListHelper.GetSongList(false, false) as List<MusicTitle>, Thread.CurrentThread.CurrentUICulture, (MusicTitle s) => { return s.Title; }, true));
    listSongs.ItemsSource = songList;
    // Set Artist List
    List<AlphaKeyGroup<MusicArtist>> artistList = await Task.Run(() => AlphaKeyGroup<MusicArtist>.CreateGroups(ListHelper.GetArtistList(false) as List<MusicArtist>, Thread.CurrentThread.CurrentUICulture, (MusicArtist ar) => { return ar.Artist; }, true));
    listArtist.ItemsSource = artistList;
    // Set Album List
    List<AlphaKeyGroup<MusicAlbum>> albumList = await Task.Run(() => AlphaKeyGroup<MusicAlbum>.CreateGroups(ListHelper.GetAlbumList(false, true) as List<MusicAlbum>, Thread.CurrentThread.CurrentUICulture, (MusicAlbum al) => { return al.Album; }, true));
    listAlbums.ItemsSource = albumList;
    // Set Genre List
    List<AlphaKeyGroup<MusicGenre>> genreList = await Task.Run(() => AlphaKeyGroup<MusicGenre>.CreateGroups(ListHelper.GetGenreList(false) as List<MusicGenre>, Thread.CurrentThread.CurrentUICulture, (MusicGenre g) => { return g.Genre; }, true));
    listGenres.ItemsSource = genreList;
    // Set PlayList
    List<AlphaKeyGroup<MusicPlaylist>> playList = await Task.Run(() => AlphaKeyGroup<MusicPlaylist>.CreateGroups(ListHelper.GetPlayList(false) as List<MusicPlaylist>, Thread.CurrentThread.CurrentUICulture, (MusicPlaylist pl) => { return pl.Playlist; }, true));
    listPlaylist.ItemsSource = playList;

}

编辑2

在我的手机中有233首歌曲,我编写的ListHelper类中的方法抛出异常,其中包括获取歌曲,专辑,播放列表,流派和艺术家的所有方法。抛出异常的方法是我获得相册的专辑封面的方法。这就是方法。

public static BitmapImage GetAlbumArt(Song song, int size = 100 )
{
    BitmapImage img = new BitmapImage(); // EXCEPTION IS THROWN HERE
    img.DecodePixelHeight = size;
    img.DecodePixelWidth = size;

    if (song.Album.HasArt)
    {               
         img.SetSource(song.Album.GetAlbumArt());
    }
    else
    {
         img.UriSource = new Uri("/Images/cover.png", UriKind.Relative);
    }
    return img;
  }

1 个答案:

答案 0 :(得分:1)

您的方法没有进行任何异步工作,因此没有理由让它返回Task。相反,如果你想让你的UI保持响应,将它包装在Task.Run内,它会在ThreadPool线程上排队:

public static object GetSongList(bool lib = true, bool albumArt = true)
{
     MediaLibrary mediaLib = new MediaLibrary();
     var songs = mediaLib.Songs;

     if (lib)
     {
          return songs;
     }
     else
     {
          var list = new List<MusicTitle>();
          foreach (var song in songs)
          {
               list.Add(new MusicTitle()
               {
                   Artist = song.Artist.Name,
                   Title = song.Name,
                   Duration = (new DateTime(song.Duration.Ticks)).ToString("mm:ss"),
                   Album = song.Album.Name, 
                   Art = albumArt ? GetAlbumArt(song, 100) : null
               });
          }

          return list;
      }
}

并在Task.Run

中使用它
var obj = await Task.Run(() => GetSongList());

作为一个不相关的附注,我建议您查看是否可以创建一个公共基类/接口作为返回类型而不是object,以确保类型安全。