简体   繁体   中英

Async method only works when MessageDialog is called

I am very new to C# and still trying to understand how async methods work. My UWP app needs to retrieve a thumbnail JPG from a compressed folder when it is dropped onto the screen, display the thumbnail with a progress ring while the folder is uploading, and then remove the progress ring when upload is complete.

First this method is triggered when the user drops a file:

private async void OnFileDrop(object sender, DragEventArgs e)
{
    if (e.DataView.Contains(StandardDataFormats.StorageItems))
    {
        var items = await e.DataView.GetStorageItemsAsync();
        if (items.Count > 0)
        {

                foreach (var appFile in items.OfType<StorageFile>())
                {

                    StorageFolder downloadFolder = ApplicationData.Current.LocalFolder;

                    StorageFolder unzipFolder =
                await downloadFolder.CreateFolderAsync(Path.GetFileNameWithoutExtension(appFile.Name),
                CreationCollisionOption.GenerateUniqueName);

                    await UnZipFileAsync(appFile, unzipFolder);

                }
        }
    }

Next:

public static IAsyncAction UnZipFileAsync(StorageFile zipFile, StorageFolder destinationFolder, Action<ZipArchiveEntry, StorageFolder> callback, Action<ZipArchiveEntry> completeCallback)
    {
        return UnZipFileHelper(zipFile, destinationFolder, thumbnailCallback, completeCallback).AsAsyncAction();
    }

Then this Task unzips the file, calling the thumbnailCallback method after the ZipArchive has been created:

 private static async Task UnZipFileHelper(StorageFile zipFile, StorageFolder destinationFolder, Action<ZipArchiveEntry, StorageFolder> thumbnailCallback, Action<ZipArchiveEntry> completeCallback)
    {
        if (zipFile == null || destinationFolder == null ||
            !Path.GetExtension(zipFile.Name).Equals(".zip", StringComparison.OrdinalIgnoreCase)
            )
        {
            throw new ArgumentException("Invalid argument...");
        }

        Stream zipMemoryStream = await zipFile.OpenStreamForReadAsync();

        // Create zip archive to access compressed files in memory stream
        using (ZipArchive zipArchive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Read))
        {
            ZipArchiveEntry thumbnail = zipArchive.GetEntry("thumbnail.jpg");

            thumbnailCallback(thumbnail, destinationFolder);

            // Unzip compressed file iteratively.
            foreach (ZipArchiveEntry entry in zipArchive.Entries)
            {
                await UnzipZipArchiveEntryAsync(entry, entry.FullName, destinationFolder);

            }
        }
    }

This is the thumbnailCallback method which is supposed to display the thumbnail while the folder is being uploaded:

public async void thumbnailCallback(ZipArchiveEntry thumbnail, StorageFolder destinationFolder)
{
        // thumbnail only displays after this has been called and user clicks OK button to close dialog
        var messageDialog = new MessageDialog("displaying thumbnail");
        await messageDialog.ShowAsync();

        // code to display thumbnail

        Canvas canvas = new Canvas();
        canvas.Width = 200;
        canvas.Height = 125;
        ProgressRing progressRing = new ProgressRing();
        progressRing.Name = thumbnail.FullName;
        progressRing.IsActive = true;
        progressRing.Height = 50;
        progressRing.Width = 50;
        Canvas.SetTop(progressRing, 35);
        Canvas.SetLeft(progressRing, 75);
        Canvas.SetZIndex(progressRing, 2);

        Image thumb = new Image();
        thumb.Name = thumbnail.FullName;
        thumb.Width = 200;
        thumb.Height = 125;
        thumb.Opacity = 0.2;

        BitmapImage bitmapImage = new BitmapImage();
        Uri uri = new Uri(destinationFolder.Path + "\\" + thumbnail.FullName);
        bitmapImage.UriSource = uri;
        thumb.Source = bitmapImage;

        canvas.Children.Add(thumb);
        canvas.Children.Add(progressRing);




    }

Right now the thumbnail will only display if MessageDialog.ShowAsync() is called first, and it does not appear until the OK button has been clicked on the dialog box.

thumbnailCallback is called without await . That's the reason thumnail are not not displayed (if you are lucky you may get thumbnail randomly :)). When you put MessageDialog then thread is enough time to execute after user interaction.

How to Fix

Call it like as below:

await thumbnailCallback(thumbnail, destinationFolder);

Suggestion :

Change the signature as

public async Task thumbnailCallback(ZipArchiveEntry thumbnail, StorageFolder destinationFolder)

Normally, you would want to return a Task . The main exception should be when you need to have a void return type (for events).

async methods that return void are special in another aspect: they represent top-level async operations, and have additional rules that come into play when your task returns an exception .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM