簡體   English   中英

如何使用async和await關鍵字進行異步調用

[英]How to make async call using async and await keyword

我正在使用支持異步和等待功能的Linq To Twitter。

我有贏的窗體應用程序,該應用程序在dll中調用方法來獲取關注者。(當前,我只是返回一個整數,但是我想返回關注者,不知道該怎么做)

 private void SubmitButton_Click(object sender, EventArgs e)
        {
            try
            {

                MessageBox.Show("Please wait for few mins");

                var maxFollowers = (MaxFollowers.Text == "") ? (int?)null : int.Parse(MaxFollowers.Text);

                var followers = TwitterHelper.GetFollowersTweets
                   (Convert.ToUInt64(TwitterUserID.Text), ConsumerKey.Text, ConsumerSecretKey.Text,
                       AccessToken.Text, AccessTokenSecret.Text, maxFollowers);


                MessageBox.Show(string.Format("Total Followers Found: {0}", followers.ToString()));

            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Something went wrong!"));
            }
        }

從Form調用的方法

  public static int GetFollowersTweets
         (ulong twitterUserId, string consumerKey, string consumerKeySecret,
           string accessToken, string accessTokenSecret, int? maxFollowers)
        {


            var auth = GetUserAuthorizationToken
               (consumerKey, consumerKeySecret,
                   accessToken, accessTokenSecret);

            var followers = GetTwitterFollowers
              (twitterUserId, auth, maxFollowers);

            var followersTweets = new List<TwitterData>();

            followers.ContinueWith((taskWithMsg) =>
                                   {
                                       followersTweets = GetFollowersTweetsList(taskWithMsg.Result, auth);
                                   });



            return 2;


            // return followersTweets;

        }

從Twitter API“ GetTwitterFollowers”獲取關注者的主要方法

 private static async Task<List<TwitterData>> GetTwitterFollowers(
         ulong twitterUserId, SingleUserAuthorizer auth, int? maxFollowers)
        {

            var followerss = maxFollowers ?? 15000;

            try
            {
                var twitterCtx = new TwitterContext(auth);
                var followers = await twitterCtx.Friendship
                                          .Where(f => f.Type == FriendshipType.FollowersList
                                              && f.UserID == twitterUserId.ToString())
                                          .Select(f => new TwitterData()
                                          {

                                              Followers = f.Users.Where(t => !t.Protected).Take(followerss).Select(s => s).ToList()
                                          }).SingleOrDefaultAsync();


                return GetFollowersList(followers.Followers);


            }
            catch (Exception ex)
            {
                return null;
            }

        }

目前,我的應用流程是這樣的

1)當從“我的表單”中提交按鈕單擊時,它將調用公共方法“ GetFollowersTweets”,然后調用內部方法“ GetTwitterFollowers”。而且此內部方法是異步的,因此當它開始獲取關注者時,控件將返回到公共方法再次,它只是將一個整數返回給窗體上的調用方...然后過了一段時間,當twitter獲取關注者時,它將從下一行繼續執行其余任務

 followers.ContinueWith((taskWithMsg) =>
                                       {
                                           followersTweets = GetFollowersTweetsList(taskWithMsg.Result, auth);
                                       });

如您所見,我只是返回一個int,而我想返回“ followersTweets”,我該怎么做? 需要哪些更改? 請幫忙

通常,不要在異步代碼中使用ContinueWith 使用await代替:

var followers = await GetTwitterFollowersAsync(twitterUserId, auth, maxFollowers);
var followersTweets = await GetFollowersTweetsListAsync(followers, auth);
return followersTweets;

按照約定 ,我還更改了異步方法,以“ Async”結尾。

這要求您更改方法的簽名:

public static async Task<List<TwitterData>> GetFollowersTweetsAsync(...)

以及事件處理程序的簽名:

private async void SubmitButton_Click(object sender, EventArgs e)
{
    ...
    var followers = await TwitterHelper.GetFollowersTweetsAsync
        (Convert.ToUInt64(TwitterUserID.Text), ConsumerKey.Text, ConsumerSecretKey.Text,
        AccessToken.Text, AccessTokenSecret.Text, maxFollowers);
    ...
}

代替

        var followers = GetTwitterFollowers(twitterUserId, auth, maxFollowers);

        var followersTweets = new List<TwitterData>();

        followers.ContinueWith((taskWithMsg) =>
                               {
                                   followersTweets = GetFollowersTweetsList(taskWithMsg.Result, auth);
                               });



        return 2;

采用

var followers = await GetTwitterFollowers(twitterUserId, auth, maxFollowers);
var followersList = await GetFollowersTweetsList(followers, auth);
return followersList.Count;

另外,您應該將GetFollowersTweets()的簽名更改為

public static async Task<int> GetFollowersTweets

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM