使用任务异步方法加载集合视图

问题描述 投票:1回答:1

我正在尝试使用带有视差服务的异步任务方法加载缩略图:

在我的pcl页面中,我有这个:

protected override void OnAppearing()
        {

            Device.BeginInvokeOnMainThread(() => UserDialogs.Instance.ShowLoading("Loading...", MaskType.Black));

            Task.Run(async () =>
            {
                directoryPath = await getThumbnails.GetBitmaps(fileInfo.FullName);
                List<ThumbnailsModel> thumbnailsModels = new List<ThumbnailsModel>();

                int i = 1;
                Directory.GetFiles(directoryPath).ToList<string>().ForEach(delegate (string thumbnailsEmplacement)
                {
                    thumbnailsModels.Add(new ThumbnailsModel(i, thumbnailsEmplacement));
                    i++;
                });
                CollectionViewThumbnails.ItemsSource = thumbnailsModels;


            }).ContinueWith(result => Device.BeginInvokeOnMainThread(() =>
            {


                UserDialogs.Instance.HideLoading();
            }
        )
        );
        }

我获取缩略图的方法:

public async Task<string> GetBitmaps(string filePath)
    {

        //TODO-- WORK ON THIS

        var appDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
        string fileName = System.IO.Path.GetFileNameWithoutExtension(filePath);
        string directoryPath = System.IO.Path.Combine(appDirectory, "thumbnailsTemp", System.IO.Path.GetFileNameWithoutExtension(fileName));

        var stream = new MemoryStream();

        using (Stream resourceStream = new FileStream(filePath, FileMode.Open))
        {
            resourceStream.CopyTo(stream);
        }

        Document document = new Document(stream);
        int count = document.Pages.Count;

        for(int i = 0; i<= count; i++) {
            TallComponents.PDF.Rasterizer.Page page = document.Pages[0];

            using (var outputStream = new FileStream(System.IO.Path.Combine(directoryPath, fileName + "Thumbnails" + i + ".png"), FileMode.Create, FileAccess.Write))
            {

                await Task.Run(() =>
                {

                    page.SaveAsBitmap(outputStream, CompressFormat.Png, 5);
                });
            }
        }

        return directoryPath;
    }

问题是,我的应用程序将在我的Dependency服务方法中运行,然后在完成缩略图之前并在这行中返回pcl OnAppearing方法中。>

UserDialogs.Instance.HideLoading();

<<

似乎您有未处理的异常。即使您正在继续的Task上抛出异常,该延续

将运行
可以在TaskContinuationOptions.OnlyOnRanToCompleted的过载中使用others(和ContinueWith)之类的方法来更改此值。如果未指定,则默认值为TaskContinuationOptions.None
或者,如果您希望它在失败时运行并对其进行处理,则可以连续访问result.Exception
c# xamarin xamarin.forms xamarin.android
1个回答
3
投票
或者,如果您希望它在失败时运行并对其进行处理,则可以连续访问result.Exception
© www.soinside.com 2019 - 2024. All rights reserved.