WP8.1 C#Windows Phone 8.1背景任务WritableBitMap线程错误



我正在尝试从背景任务中更新频段我的瓷砖图像,并且在WritableBitMap上获得以下错误:

System.Exception: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
   at Windows.UI.Xaml.Media.Imaging.WriteableBitmap..ctor(Int32 pixelWidth, Int32 pixelHeight)
   at BackgroundTaskCS.UpdateBandTask.<LoadImage>d__f.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

看起来可写入的bitbitmap需要在UI线程上运行,但是我认为我无法访问UI线程,因为我需要在不打开应用程序的情况下更新瓷砖。有其他解决方案吗?

以下是我正在使用的任务。预先感谢。

我在这里开始这个问题,并因乐队而被引导到Stackoverflow。

public async void Run(IBackgroundTaskInstance taskInstance)
        {
            BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
             await UpdateMeTile();
            Debug.WriteLine("CS Task Run");
            _deferral.Complete();
        }
        private static async Task UpdateMeTile()
        {
            /// <summary>
            /// Connect to Microsoft Band and change the wallpaper.
            /// </summary>
            try
            {
                // Get the list of Microsoft Bands paired to the phone.
                IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();
                if (pairedBands.Length < 1)
                {
                    return;
                }
                // Connect to Microsoft Band.
                using (IBandClient bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
                {
                    // Change the wallpaper.
                    await bandClient.PersonalizationManager.SetMeTileImageAsync(await LoadImage("ms-appx:///Assets/SampleMeTileImage.jpg"));
                }
            }
            catch (Exception ex)
            {
                //this.textBlock.Text = ex.ToString();
                Debug.WriteLine("!!!!!!!!!!!!!!!!!!Exception. {0}", ex);
            }
        }

        private static async Task<BandImage> LoadImage(string uri)
        {
            StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(uri));
            using (IRandomAccessStream fileStream = await imageFile.OpenAsync(FileAccessMode.Read))
            {
                WriteableBitmap bitmap = new WriteableBitmap(1, 1);
                await bitmap.SetSourceAsync(fileStream);
                bitmap.ToBandImage();
                return bitmap.ToBandImage();
            }
        }

如Rob Caplan在原始MSDN论坛帖子中提到的那样,请确保从XamlrenderingBackgroundTask派生您的背景任务。这样做将确保您的背景任务的onrun()方法将在" UI线程"上调用(目的是使用与UI相关类型,例如WritableBitMap)。

最新更新