Update ImageLoader.cs

This commit is contained in:
ClemensFischer 2025-08-21 21:48:08 +02:00
parent 178cec8e66
commit 6f82f8012a

View file

@ -2,8 +2,8 @@
using System; using System;
using System.IO; using System.IO;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks;
using System.Threading; using System.Threading;
using System.Threading.Tasks;
#if WPF #if WPF
using System.Windows.Media; using System.Windows.Media;
#elif UWP #elif UWP
@ -105,16 +105,7 @@ namespace MapControl
{ {
if (responseMessage.IsSuccessStatusCode) if (responseMessage.IsSuccessStatusCode)
{ {
byte[] buffer; byte[] buffer = await responseMessage.Content.ReadAsByteArrayAsync(progress, cancellationToken).ConfigureAwait(false);
if (progress != null && responseMessage.Content.Headers.ContentLength.HasValue)
{
buffer = await responseMessage.Content.ReadAsByteArrayAsync(progress, cancellationToken).ConfigureAwait(false);
}
else
{
buffer = await responseMessage.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
}
response = new HttpResponse(buffer, responseMessage.Headers.CacheControl?.MaxAge); response = new HttpResponse(buffer, responseMessage.Headers.CacheControl?.MaxAge);
} }
@ -148,27 +139,36 @@ namespace MapControl
{ {
public static async Task<byte[]> ReadAsByteArrayAsync(this HttpContent content, IProgress<double> progress, CancellationToken cancellationToken) public static async Task<byte[]> ReadAsByteArrayAsync(this HttpContent content, IProgress<double> progress, CancellationToken cancellationToken)
{ {
var length = (int)content.Headers.ContentLength.Value; byte[] buffer;
var buffer = new byte[length];
using (var stream = await content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false)) if (progress != null && content.Headers.ContentLength.HasValue)
{ {
int offset = 0; var length = (int)content.Headers.ContentLength.Value;
int read; buffer = new byte[length];
while (offset < length && using (var stream = await content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false))
(read = await stream.ReadAsync(buffer, offset, length - offset, cancellationToken).ConfigureAwait(false)) > 0)
{ {
cancellationToken.ThrowIfCancellationRequested(); int offset = 0;
int read;
offset += read; while (offset < length &&
(read = await stream.ReadAsync(buffer, offset, length - offset, cancellationToken).ConfigureAwait(false)) > 0)
if (offset < length) // 1.0 reported by caller
{ {
progress.Report((double)offset / length); cancellationToken.ThrowIfCancellationRequested();
offset += read;
if (offset < length) // 1.0 reported by caller
{
progress.Report((double)offset / length);
}
} }
} }
} }
else
{
buffer = await content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
}
return buffer; return buffer;
} }