using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
+using System.Threading;
using System.Threading.Tasks;
using static Interop;
using static Interop.Decode;
}
}
- internal Task<IEnumerable<BitmapFrame>> DecodeAsync()
+ private IEnumerable<BitmapFrame> RunDecoding()
{
- Initialize(Handle);
+ IntPtr outBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));
+ Marshal.WriteIntPtr(outBuffer, IntPtr.Zero);
- IntPtr outBuffer = IntPtr.Zero;
- SetOutputBuffer(Handle, out outBuffer).ThrowIfFailed("Failed to decode given image");
+ try
+ {
+ SetOutputBuffer(Handle, outBuffer).ThrowIfFailed("Failed to decode given image");
- var tcs = new TaskCompletionSource<IEnumerable<BitmapFrame>>();
+ DecodeRun(Handle, out var width, out var height, out var size).
+ ThrowIfFailed("Failed to decode");
- Task.Run(() =>
+ yield return new BitmapFrame(Marshal.ReadIntPtr(outBuffer), width, height, (int)size);
+ }
+ finally
{
- try
+ if (Marshal.ReadIntPtr(outBuffer) != IntPtr.Zero)
{
- int width, height;
- ulong size;
+ LibcSupport.Free(Marshal.ReadIntPtr(outBuffer));
+ }
- DecodeRun(Handle, out width, out height, out size).ThrowIfFailed("Failed to decode");
+ Marshal.FreeHGlobal(outBuffer);
+ }
+ }
- tcs.SetResult(new[] { new BitmapFrame(outBuffer, width, height, (int)size) });
- }
- catch (Exception e)
- {
- tcs.TrySetException(e);
- }
- finally
- {
- LibcSupport.Free(outBuffer);
- }
- });
+ internal Task<IEnumerable<BitmapFrame>> DecodeAsync()
+ {
+ Initialize(Handle);
- return tcs.Task;
+ return Task.Factory.StartNew(RunDecoding, CancellationToken.None,
+ TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning,
+ TaskScheduler.Default);
}
internal virtual void Initialize(ImageDecoderHandle handle)
internal static extern ImageUtilError SetInputBuffer(ImageDecoderHandle handle, byte[] srcBuffer, ulong srcSize);
[DllImport(Libraries.ImageUtil, EntryPoint = "image_util_decode_set_output_buffer")]
- internal static extern ImageUtilError SetOutputBuffer(ImageDecoderHandle handle, out IntPtr dstBuffer);
+ internal static extern ImageUtilError SetOutputBuffer(ImageDecoderHandle handle, IntPtr dstBuffer);
[DllImport(Libraries.ImageUtil, EntryPoint = "image_util_decode_set_colorspace")]
internal static extern ImageUtilError SetColorspace(ImageDecoderHandle handle, ImageColorSpace colorspace);