using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
+using System.Threading;
using System.Threading.Tasks;
using static Interop;
using static Interop.Decode;
var pathPtr = Marshal.StringToHGlobalAnsi(inputFilePath);
try
{
-
SetInputPath(Handle, pathPtr).ThrowIfFailed("Failed to set input file path for decoding");
return await DecodeAsync();
}
}
}
- 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)