0

J'utilise Xamarin et je télécharge de nombreuses images pour un GridView.Conversion d'une fonction de téléchargement pour être asynchrone

Voici mon code que j'appelle pour chaque image:

private Bitmap GetImageBitmapFromUri(string uri) 
{ 
    Bitmap imageBitmap = null; 

    using (var webClient = new WebClient()) 
    { 
     var imageBytes = webClient.DownloadData(uri); 
     if (imageBytes != null && imageBytes.Length > 0) 
     { 
      imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length); 
     } 
    } 

    return imageBitmap; 
} 

Quelqu'un peut-il me s'il vous plaît aider à rendre ce code ci-dessus asynchrone?

Merci à l'avance

+0

Quelle est votre version de Xamarin.Android? 4,8+ ou moins de 4,8? – Coder

+0

Ma version Xamarin.Android est 4.8+ – user3736648

Répondre

0

Ceci est l'équivalent C# AsyncTask qui se trouve en JAVA:

public class DownloadBitmap : AsyncTask 
{ 
    protected override void OnPreExecute() 
    { 
     //launch loading dialog.. before your main task 
    } 

    protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params) 
    { 
     //download your Bitmap 
    } 

    protected override void OnPostExecute(Java.Lang.Object result) 
    { 
     //return your Bitmap to update the UI 
    } 
} 

=> Informations complémentaires here

1

Vous pouvez utiliser Async/Await avec la méthode de DownloadDataTaskAsyncWebClient pour rendre votre code asynchrone comme defined here with example:

async Task<Bitmap> downloadAsync(object sender, System.EventArgs ea) 
{ 
    WebClient webClient = new WebClient(); 
    var url = new Uri("http://photojournal.jpl.nasa.gov/jpeg/PIA15416.jpg"); 
    byte[] bytes = null; 

    try{ 
    bytes = await webClient.DownloadDataTaskAsync(url); 
    } 
    catch(TaskCanceledException){ 
    // Exception 
    return; 
    } 
    catch(Exception e){ 
    // Exception 
    return; 
    } 

    Bitmap bitmap = await BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length); 

    return bitmap;  
} 
Questions connexes