From 2f4927f7190fae6166408ed47a3afaeec8d7858f Mon Sep 17 00:00:00 2001 From: nyne Date: Sat, 30 Nov 2024 21:30:39 +0800 Subject: [PATCH] prevent too many image loading at save time --- .../image_provider/cached_image.dart | 35 +++++++++++++------ 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/lib/foundation/image_provider/cached_image.dart b/lib/foundation/image_provider/cached_image.dart index 701eb76..be5cd4a 100644 --- a/lib/foundation/image_provider/cached_image.dart +++ b/lib/foundation/image_provider/cached_image.dart @@ -21,22 +21,35 @@ class CachedImageProvider final String? cid; + static int loadingCount = 0; + + static const _kMaxLoadingCount = 8; + @override Future load(StreamController chunkEvents) async { - if(url.startsWith("file://")) { - var file = File(url.substring(7)); - return file.readAsBytes(); + while(loadingCount > _kMaxLoadingCount) { + await Future.delayed(const Duration(milliseconds: 100)); } - await for (var progress in ImageDownloader.loadThumbnail(url, sourceKey, cid)) { - chunkEvents.add(ImageChunkEvent( - cumulativeBytesLoaded: progress.currentBytes, - expectedTotalBytes: progress.totalBytes, - )); - if(progress.imageBytes != null) { - return progress.imageBytes!; + loadingCount++; + try { + if(url.startsWith("file://")) { + var file = File(url.substring(7)); + return file.readAsBytes(); } + await for (var progress in ImageDownloader.loadThumbnail(url, sourceKey, cid)) { + chunkEvents.add(ImageChunkEvent( + cumulativeBytesLoaded: progress.currentBytes, + expectedTotalBytes: progress.totalBytes, + )); + if(progress.imageBytes != null) { + return progress.imageBytes!; + } + } + throw "Error: Empty response body."; + } + finally { + loadingCount--; } - throw "Error: Empty response body."; } @override