简体   繁体   中英

Xamarin.iOS async await method not working

I'm developing an iOS app in Xamarin in C#, I have a method, that must be called in Asynchronous mode. I got this guideline, but it seems to be different from my needs.

I tried to do this:

var tasks = new List<Task<UIImage>>();
            var imageUrls = new[] {
                "http://www.mySite/images/02.jpg",
                "http://www.mySite/images/03.jpg",
                "http://www.mySite/images/04.jpg",
                "http://www.mySite/images/05.jpg",
                "http://www.mySite/images/06.jpg",
                "http://www.mySite/images/07.jpg",
                "http://www.mySite/images/08.jpg",
                "http://www.mySite/images/09.jpg",
                "http://www.mySite/images/10.jpg",
                "http://www.mySite/images/11.jpg",
                "http://www.mySite/images/12.jpg",
                "http://www.mySite/images/3.jpg",
                "http://www.mySite/images/14.jpg",
                "http://www.mySite/images/15.jpg"

            };
    foreach (var imageUrl in imageUrls)
            {
                var task = getImageFromUrl(imageUrl);
                tasks.Add(task);
            }
            var images = await Task.WhenAll(tasks);

the called method is:

async Task<UIImage> getImageFromUrl(string uri)
    {
        using (var url = new NSUrl(uri))
        using (var data = NSData.FromUrl(url))
            return UIImage.LoadFromData(data);
    }

it runs synchronously, and shows me the following warning:

Warning CS1998: Async block lacks `await' operator and will run synchronously (CS1998)

What am I missing in my code? It seems that the getImageFromUrl() method misses an async property. Are there other way to load images from url asynchrously?

The code you have shown in your example is not asynchronous. If you want to load all 6 images, you probably want to have something like this:

var tasks = new List<Task<UIImage>>();
var imageUrls = new[] {"http://www.mySite/images/02.jpg", ... "http://www.mySite/images/09.jpg"};
foreach (var imageUrl in imageUrls) {
  var task = // invoke a method which loads an image asynchronously and returns a Task, but don't call await on this Task
  tasks.Add(task);
}
var images = await Task.WhenAll(tasks);

Also, the code that you have in getImageFromUrl does not invoke any asynchronous methods. You may consider using HttpClient.GetByteArrayAsync to load data asynchronously and then create an Image from this byte array:

async Task<UIImage> getImageFromUrl(string uri)
{
    using (var httpClient = new HttpClient())
    var imageBytes = await httpClient.GetByteArrayAsync(uri);
    var image = // create image from imageBytes;
    return image;
}

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