From 71d915f3ef51f97bc5e94b328834e8f864d3f52a Mon Sep 17 00:00:00 2001 From: tangge233 Date: Wed, 9 Oct 2024 00:14:05 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20UseCache=20=E9=80=89=E9=A1=B9=E5=92=8C?= =?UTF-8?q?=E5=BC=82=E6=AD=A5=E5=8A=A0=E8=BD=BD=E5=9B=BE=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Plain Craft Launcher 2/Controls/MyImage.vb | 44 +++++++++++++++++++++- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/Plain Craft Launcher 2/Controls/MyImage.vb b/Plain Craft Launcher 2/Controls/MyImage.vb index 5e09175..add3306 100644 --- a/Plain Craft Launcher 2/Controls/MyImage.vb +++ b/Plain Craft Launcher 2/Controls/MyImage.vb @@ -1,9 +1,24 @@ -Public Class MyImage +Imports System.Threading.Tasks + +Public Class MyImage Inherits Image '事件 Private _SourceData As String = "" + Private _UseCache As Boolean = False + Private _DownloadTask As Task + + Private FileCacheExpiredTime As TimeSpan = New TimeSpan(7, 0, 0, 0) ' 一个星期的缓存有效期 + + Public Property UseCache As Boolean + Get + Return _UseCache + End Get + Set(value As Boolean) + _UseCache = value + End Set + End Property ''' ''' 重写Image的Source属性 @@ -15,7 +30,32 @@ Set(value As String) If String.IsNullOrEmpty(value) Then Exit Property _SourceData = value - MyBase.Source = New MyBitmap(_SourceData) + If Not value.StartsWithF("http") Then ' 本地资源直接使用 + MyBase.Source = New MyBitmap(_SourceData) + Exit Property + End If + If _DownloadTask IsNot Nothing AndAlso Not _DownloadTask.IsCompleted Then ' 之前下载任务还在,直接砍了 + _DownloadTask.Dispose() + End If + Dim NeedDownload As Boolean = True '是否需要下载/本地是否有有效缓存 + Dim TempFilePath As String = PathTemp & "Cache\MyImage\" & GetHash(_SourceData) & ".png" + If _UseCache And File.Exists(TempFilePath) And (DateTime.Now - File.GetCreationTime(TempFilePath)) < FileCacheExpiredTime Then NeedDownload = False ' 缓存文件存在且未过期,不需要重下 + If Not NeedDownload Then + MyBase.Source = New MyBitmap(TempFilePath) + Exit Property + End If + ' 异步下载图片 + Dim TaskID = 0 + _DownloadTask = New Task(Sub() + NetDownload(_SourceData, TempFilePath, True) + End Sub) + TaskID = _DownloadTask.Id + _DownloadTask.Start() + _DownloadTask.ContinueWith(Sub(t) + If t.IsCompleted AndAlso t.Id = TaskID Then ' 任务没有被干掉 + MyBase.Source = New MyBitmap(TempFilePath) + End If + End Sub, TaskScheduler.FromCurrentSynchronizationContext()) End Set End Property Public Shared Shadows ReadOnly SourceProperty As DependencyProperty = DependencyProperty.Register("Source", GetType(String), GetType(MyImage), New PropertyMetadata(New PropertyChangedCallback(