forked from amkovkov/GranuSightSoftware2
feat: safe image loading
add AsyncImageViewModel that loading images sequentially
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Media.Imaging;
|
||||
using Avalonia.Threading;
|
||||
|
||||
using GSS2.Core.Analysis.AmineContent.Database.Calibration;
|
||||
|
||||
namespace GSS2.UI.Core.ViewModels;
|
||||
|
||||
public partial class AsyncImageRecordViewModel : ViewModelBase
|
||||
{
|
||||
private static readonly SemaphoreSlim _semaphore = new(1, 1);
|
||||
|
||||
private readonly string _path;
|
||||
|
||||
[ObservableProperty] private ImageRecord _imageRecord;
|
||||
[ObservableProperty] private IImage? _image;
|
||||
[ObservableProperty] private bool _isLoading = true;
|
||||
|
||||
public AsyncImageRecordViewModel(string path, ImageRecord imageRecord)
|
||||
{
|
||||
_path = path;
|
||||
_imageRecord = imageRecord;
|
||||
_ = LoadAsync();
|
||||
}
|
||||
|
||||
private async Task LoadAsync()
|
||||
{
|
||||
await _semaphore.WaitAsync();
|
||||
|
||||
try
|
||||
{
|
||||
var bitmap = await Task.Run(() => new Bitmap(_path));
|
||||
|
||||
await Dispatcher.UIThread.InvokeAsync(() =>
|
||||
{
|
||||
Image = bitmap;
|
||||
IsLoading = false;
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
await Dispatcher.UIThread.InvokeAsync(() => IsLoading = false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_semaphore.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user