枚举相机胶卷图片会引发invalidoperationexception

时间:2013-11-12 21:53:57

标签: c# windows-phone-7 windows-phone-8 windows-phone-7.1

以下代码抛出invalidOperationException但仅在分离调试器时抛出。代码目标7.1并且不时用户报告问题。这是我第一次在Windows Phone 8设备上重现此问题,但只有在我分离调试器时。附加调试器后,代码运行得非常好。问题不是一致的重复。在分析中,我看到有一小部分用户面临这个问题。知道这里发生了什么吗?

       PictureAlbum localRoll = media.GetCameraRoll();
       foreach (Picture pic in localRoll.Pictures) // exception here
       {

       }


        public PictureAlbum GetCameraRoll()
        {
        // Work around for known bug in the media framework.  Hits the static constructors
        // so the user does not need to go to the picture hub first.
        MediaPlayer.Queue.ToString();

        MediaLibrary ml = null;
        PictureAlbum cameraRoll = null;

        foreach (MediaSource source in MediaSource.GetAvailableMediaSources())
        {
            if (source.MediaSourceType == MediaSourceType.LocalDevice)
            {
                ml = new MediaLibrary(source);

                PictureAlbumCollection allAlbums = ml.RootPictureAlbum.Albums;

                foreach (PictureAlbum album in allAlbums)
                {
                    if (album.Name == "Camera Roll")
                    {
                        cameraRoll = album;
                        return cameraRoll;
                    }
                }
            }
        }

        return null;
    }

System.InvalidOperationException:发生了意外错误。 在 Microsoft.Xna.Framework.Media.MediaLibraryEnumerator'1.System.Collection.Ienumerator'1.get_Item(Int32 index)

2 个答案:

答案 0 :(得分:2)

非常奇怪,但有效。首先在图片上调用OrderBy不会引发异常。

                var a = localRoll.Pictures;

                foreach (Picture pic in a.OrderBy(x=>x.Date))
                {

                }

答案 1 :(得分:0)

请检查localRolllocalRoll.Pictures != null以及localRoll.Pictures.Count > 0,因为某些手机可能有0张图片且代码试图在null集合上进行迭代。

   PictureAlbum localRoll = media.GetCameraRoll();
   if(localRoll != null)
   {
      if(localRoll.Pictures != null)
      {
          if(localRoll.Pictures.Count > 0)
          {
             foreach (Picture pic in localRoll.Pictures)
             {

             }
          }
      }
   }