2016-03-22 6 views
0

私はvoid戻り値の型を持つ非同期メソッドを持っています。ここでは、私はどこでもそれを使用することができますので、それは私がいくつかのデータをロードするために1つのページにそれを使用し、それが正常に動作し、それがこの方法を完了した後、次のコードに前進し、公共の静的メソッドであるuwp非同期メソッドコード行をスキップする

public static async void LoadPlaylists() 
{ 
    if(playlistitems.Count==0) 
    { 
     var playlists = await ApplicationData.Current.LocalFolder.GetFilesAsync(); 
     var c = playlists.Count; 
     foreach (var playlist in playlists) 
     { 
      var p = await Playlist.LoadAsync(playlist); 
      var image = new BitmapImage(); 
      if (p.Files.Count == 0) 
      { 
       image.UriSource = new Uri("ms-appx:///Assets/Wide310x150Logo.scale-200.png"); 
      } 
      else 
      { 
       image = await Thumbnail(p.Files[0]); 
      } 
      playlistitems.Add 
      (
       new PlaylistItem 
       { 
        playlist = p, 
        PlaylistName = playlist.DisplayName, 
        NumOfVid = p.Files.Count.ToString(), 
        Thumbnail = image 
       } 
      ); 
     } 
    } 
} 

ですライン。

private void l1_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    //some more code 
    LoadPlaylists(); 
    //some more code 
} 

下に示す。しかし、私は非同期メソッドではありません別のイベントハンドラ、内の別のページにそれを使用する場合、それだけで最初の行を実行し、それが全体の方法をスキップして前方に移動します。私はそれがスキップしていることを確かに知っています。私はブレークポイントでチェックしました。私はそれが非同期だからスキップしているのを知っていますが、私はそれを望んでいません。私は次のコード行には何の問題もありません。私は再び下のコードを貼り付けています。

public static async void LoadPlaylists() 
{ 
    if(playlistitems.Count==0) 
    { 
     //it runs till here, when compiler goes to line below 
     //it skips whole methods and exits it. 
     var playlists = await ApplicationData.Current.LocalFolder.GetFilesAsync(); 
     var c = playlists.Count; 
     foreach (var playlist in playlists) 
     { 
      var p = await Playlist.LoadAsync(playlist); 
      var image = new BitmapImage(); 
      if (p.Files.Count == 0) 
      { 
       image.UriSource = new Uri("ms-appx:///Assets/Wide310x150Logo.scale-200.png"); 
      } 
      else 
      { 
       image = await Thumbnail(p.Files[0]); 
      } 

      playlistitems.Add 
      (
       new PlaylistItem 
       { 
        playlist = p, 
        PlaylistName = playlist.DisplayName, 
        NumOfVid = p.Files.Count.ToString(), 
        Thumbnail = image 
       } 
      ); 
     } 
    } 
} 

ここで私は非同期イベントハンドラでこのコードを使用しており、問題が発生しています。

private async void ME_MediaOpened(object sender, RoutedEventArgs e) 
    { 

     //When used here, it just skippes everything in the method 
     //as i described on the comments in code above. 

     LoadPlaylists(); 

     //after skipping the compiler comes here and tries to execute 
     //the lines below, which obviously causes exceptions because 
     above method was never completed to begin with. 

     var sd = playlistitems.Count; 
     //some more code 
    } 
+1

メソッドが完了するのを待つことができるように、voidではなくTaskを返します。 – Archana

答えて

3

メソッドの完了を待つことができるように、voidではなくTaskを返す必要があります。

+0

非同期プログラミングは常に私に感謝します:) –