MAUI Progressbar should display the progress live

I have a small problem. I am currently working with MAUI and the topic of downloading a file / folder from an API. The download works so far. However, I would now like to display this in a progress bar. However, this only works if the file has already been completely downloaded. However, I would like to be able to view any progress live.
Can you help me with this? Here are 3 code snippets.

One from the ViewModel:

public class DownloadQueueViewModel : INotifyPropertyChanged
{
    public ICommand AddDownloadCommand => new Command(AddDownloadToQueue);

    private Queue<DownloadQueueModel> _downloadQueueModels = new Queue<DownloadQueueModel>();
    private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
    private IApiClient _client;
    public ObservableCollection<DownloadQueueModel> Downloads { get; set; } = new ObservableCollection<DownloadQueueModel>();

    public DownloadQueueViewModel()
    {
        Task.Run(async () =>
        {
            AddDownloadToQueue();
        });
    }

    public void AddDownloadToQueue()
    {
        Task.Run(async () =>
        {
            while (!_cancellationTokenSource.Token.IsCancellationRequested)
            {
                var downloadQueue = new DownloadQueueModel { FileName = "fileName" };
                _downloadQueueModels.Enqueue(downloadQueue);
                Downloads.Add(downloadQueue);
                await ProcessQueueAsync(downloadQueue);
                await Task.Delay(1000);
            }
        }, _cancellationTokenSource.Token);
    }

    private async Task ProcessQueueAsync(DownloadQueueModel downloadQueue)
    {
        while (_downloadQueueModels.Count > 0)
        {
            downloadQueue = _downloadQueueModels.Dequeue();
            _client = new APIClient();

            var statusAction = new Action<StatusDownload>(status =>
            {
                downloadQueue.StatusDownload = status;
            });

            var progress = new Progress<long>(totalRead =>
            {
                downloadQueue.TotalBytes = totalRead;
                if (downloadQueue.FileSize > 0)
                {
                    downloadQueue.Progress = (double)totalRead / downloadQueue.FileSize * 100;
                }
            });

            string filePath = Path.Combine(Path.GetTempPath(), downloadQueue.FileName);

            try
            {
                downloadQueue.StatusDownload = StatusDownload.Downloading;
                var fileInfo = await _client.DownloadFileAsync("https://github.com/pterodactyl/panel/files/10056889/egg-file-download-error-test.zip",
                    statusAction,
                    filePath,
                    progress);

                downloadQueue.FileName = fileInfo.FullName;
            }
            catch (Exception ex)
            {
                downloadQueue.StatusDownload = StatusDownload.Failed;
            }
        }
    }

Then from my client :

public async Task<FileInfo> DownloadFileAsync(string url, Action<StatusDownload> statusDownload, string filePath, IProgress<long> progress)
{
    using (var response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
    {
        response.EnsureSuccessStatusCode();
        if (response.IsSuccessStatusCode)
        {
            statusDownload(StatusDownload.Running);
            var totalBytes = response.Content.Headers.ContentLength;

            using (var stream = await response.Content.ReadAsStreamAsync())
            using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                statusDownload(StatusDownload.Downloading);
                var buffer = new byte[8192];
                long totalRead = 0;
                int bytesRead;

                while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    await fileStream.WriteAsync(buffer, 0, bytesRead);
                    totalRead += bytesRead;

                    if (totalBytes.HasValue)
                    {
                        long percentage = totalRead * 100 / totalBytes.Value;
                        progress?.Report(percentage);
                    }
                }
                statusDownload(StatusDownload.Ready);
            }
        }
        return new FileInfo(filePath);
    }

And finally from my UI :

 <Button Text="Add Download" Command="{Binding AddDownloadCommand}" />
 <ListView ItemsSource="{Binding Downloads}">
     <ListView.ItemTemplate>
         <DataTemplate>
             <ViewCell>
                 <StackLayout Orientation="Vertical" Padding="10">
                     <Label Text="{Binding FileName}" />
                     <ProgressBar Progress="{Binding Progress, Converter={StaticResource DoubleToProgressConverter}}" />
                     <Label Text="{Binding TotalBytes}" />
                     <Label Text="{Binding StatusDownload}" />
                 </StackLayout>
             </ViewCell>
         </DataTemplate>
     </ListView.ItemTemplate>
 </ListView>

Thank you very much for your help!

Attempts have already been made to work with Action. The function is actually available, but only if the download is complete as described. I have also tried in :

while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)

to include the current status of the progress or action. But since this doesn’t work either, I’m at a bit of a loss

New contributor

Groot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật