Methode async

Résolu
contender59 Messages postés 3 Date d'inscription lundi 18 juin 2012 Statut Membre Dernière intervention 27 juin 2012 - 18 juin 2012 à 11:13
contender59 Messages postés 3 Date d'inscription lundi 18 juin 2012 Statut Membre Dernière intervention 27 juin 2012 - 18 juin 2012 à 16:02
Bonjour a tous!
Merci de m'accorder un peu de votre temps

J'ai une petite methode qui récupère des tweets sur Twitter en fonction d'un tag particulier.
J'aimerai rendre cette méthode Asynchrone pour quel ne freeze pas toute mon application.

public static List<Tweet> GetSearchResults(string searchString)
{
    using (WebClient web = new WebClient())
    {
        //More parameters then this. Most important is the page paramater. You can &page=1 to xxx. 
        //few parameters  in the url :     &rpp=100    for 100answer  |   %23 for hashtag | lang=en  for english msg......
        //  exemple: http://search.twitter.com/search.atom?lang=en&rpp=100&q=%23AnHashTag-filter:retweets
        // -filter:retweets   delete  duplicates
 
        string url = string.Format("http://search.twitter.com/search.atom?lang=en&q=%23{0}", searchString); //HttpUtility.UrlEncode(searchString)
                WebClient client = new WebClient();
 
        #region AsABrowser
        //Pretend to be Google Chrome
        //Pretending to be a browser instead of an app seems to make twitter respond faster
        client.Headers.Add("Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
        client.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3");
        client.Headers.Add("Accept-Language: en-US,en;q=0.8");
        client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.204 Safari/534.16");
        #endregion
        #region TweetFormat
        XDocument doc = XDocument.Load(url);
        XNamespace ns = "http://www.w3.org/2005/Atom";
        List<Tweet> tweets = (from item in doc.Descendants(ns + "entry")
                  select new Tweet
                  {
                     Id = item.Element(ns + "id").Value,
                     Published = DateTime.Parse(item.Element(ns + "published").Value),
                     Title = item.Element(ns + "title").Value,
                     Content = item.Element(ns + "content").Value,
                     Link = (from XElement x in item.Descendants(ns + "link")
                                where x.Attribute("type").Value == "text/html"
                                select x.Attribute("href").Value).First(),
                     Image = (from XElement x in item.Descendants(ns + "link")
                                where x.Attribute("type").Value == "image/png"
                                select x.Attribute("href").Value).First(),
                     Author = new Author()
                              {
                                 Name = item.Element(ns + "author").Element(ns + "name").Value,
                                 Uri = item.Element(ns + "author").Element(ns + "uri").Value
                              }
                }).ToList();
        return tweets;
        #endregion
     }
}




J'ai regardé pas mal d'explication sur le net, mais rien me permettant de récupérer ma list de tweet a la fin.

Quelqu'un saurait-il m'aider ?

merci beaucoup

2 réponses

contender59 Messages postés 3 Date d'inscription lundi 18 juin 2012 Statut Membre Dernière intervention 27 juin 2012
18 juin 2012 à 16:02
Problème résolue :)
Je poste si besoin ;)

public static void GetSearchResultsAsync(string searchString, Action<List<Tweet>> callback)
        {
            ThreadPool.QueueUserWorkItem((WaitCallback)(o =>
           {
               var results = GetSearchResults(searchString);
               callback(results);
           }));
        }



Et dans mon control :
TweetSearch.GetSearchResultsAsync((String)args.NewValue, new Action<List<Tweet>>(delegate(List<Tweet> tweetList)
                     {
                         customControlInstance.Dispatcher.Invoke(new Action(delegate{
                         customControlInstance.m_PartlstTweets.ItemsSource = tweetList;
                         } ));
 
                     }));


Bonne journée !
3
krimog Messages postés 1860 Date d'inscription lundi 28 novembre 2005 Statut Membre Dernière intervention 14 février 2015 49
18 juin 2012 à 14:51
Salut,

Le problème de l'asynchrone est surtout de se remettre sur le thread graphique pour l'affichage des résultats.

Déjà, un moyen très simple : la classe BackgroundWorker.
Tu crées un champ List<Tweet> dans ta classe. Tu mets les résultats de ta méthode dans ce champ.
Tu abonnes ta méthode (ou tu abonnes une méthode qui appelle ta méthode) à l'événement DoWork du BackgroundWorker.
Tu abonnes ensuite la méthode qui affiche les résultats (depuis le champ que je t'ai demandé de créer) à l'événement RunWorkerCompleted.

Une fois que c'est fait, lorsque tu veux lancer ta recherche asynchrone, tu appelles juste monBackgroundWorker.RunWorkerAsync();

Krimog : while (!(succeed = try())) ;
- Nous ne sommes pas des décodeurs ambulants. Le style SMS est prohibé. -
0
Rejoignez-nous