如何使用async和await关键字进行异步调用

时间:2014-03-04 23:35:36

标签: c# async-await

我正在使用支持异步和等待功能的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!"));
            }
        }

从表格

调用的方法
  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)当从MY Form中单击提交按钮时,它调用公共方法“GetFollowersTweets”然后调用内部方法“GetTwitterFollowers”..并且这个内部方法是异步的,所以当它开始提取关注者时,控件返回到再次使用公共方法,它只是将一个整数返回给表单上的调用者......过了一段时间,当twitter获取关注者时,它会从下面的行继续执行剩下的任务

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

正如你所看到的,我只是返回一个int,而不想返回“followersTweets”,我怎么能这样做?需要进行哪些更改?请帮忙

2 个答案:

答案 0 :(得分:1)

作为一般规则,请勿在异步代码中使用ContinueWith;改为使用await

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

我还将您的异步方法更改为以“Async”结尾,by convention

这需要更改方法的签名:

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);
    ...
}

答案 1 :(得分:0)

而不是

        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