I am working on a UWP app using Visual Studio 2017. In the app there is a task that takes a BitmapImage and apply a color to it. The task exists on both the MainPage.Xaml.cs and a background task called BackgroundTask.cs.
private static async Task<WriteableBitmap> GetImageFile(Uri fileUri)
{
StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(fileUri);
WriteableBitmap writeableBitmap = null;
using (IRandomAccessStream imageStream = await imageFile.OpenReadAsync())
{
BitmapDecoder bitmapDecoder = await BitmapDecoder.CreateAsync(imageStream);
BitmapTransform dummyTransform = new BitmapTransform();
PixelDataProvider pixelDataProvider =
await bitmapDecoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied, dummyTransform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.ColorManageToSRgb);
byte[] pixelData = pixelDataProvider.DetachPixelData();
writeableBitmap = new WriteableBitmap(
(int)bitmapDecoder.OrientedPixelWidth,
(int)bitmapDecoder.OrientedPixelHeight);
using (Stream pixelStream = writeableBitmap.PixelBuffer.AsStream())
{
await pixelStream.WriteAsync(pixelData, 0, pixelData.Length);
}
}
return writeableBitmap;
}
The code works perfectly on the MainPage. However, when trying to run in the background, Visual Studio starts an exception with no clear reasons at a much earlier stage of the code:
System.Exception: 'The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))'
The code is interrupted at this stage:
byte[] pixelData = pixelDataProvider.DetachPixelData();
writeableBitmap = new WriteableBitmap(
(int)bitmapDecoder.OrientedPixelWidth,
(int)bitmapDecoder.OrientedPixelHeight);
using (Stream pixelStream = writeableBitmap.PixelBuffer.AsStream())
{
await pixelStream.WriteAsync(pixelData, 0, pixelData.Length);
}
Using this solution gives me this error:
System.Runtime.InteropServices.COMException: 'A method was called at an unexpected time.
Could not create a new view because the main window has not yet been created'
the background task does not change the UI and do not need a window to be created! I don't know the reason behind this interruption and I don't know what information is needed to fix it. Does anyone have any experience with this?
User contributions licensed under CC BY-SA 3.0