我正在使用Linq到支持異步和等待功能的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)當從我的形式提交按鈕點擊,它調用的公共方法「GetFollowersTweets」,然後調用內部方法「GetTwitterFollowers」。而這種內部方法是異步,所以當它開始提取追隨者時,控制器會再次返回到公共方法,並且它會簡單地向表單上的調用者返回一個整數...並且在某些時候,當Twitter取回追隨者時,它會從其他任務中恢復下面的行
followers.ContinueWith((taskWithMsg) =>
{
followersTweets = GetFollowersTweetsList(taskWithMsg.Result, auth);
});
正如你所看到的,我只是返回一個int,而是我想返回「followersTweets」,我該怎麼做?需要進行哪些更改?請幫助
我只是做了這些改變。但它不會將控制權歸還給Form ..代碼在程序集內正確執行。任何建議? – user2866746
我把一個Messagebox.show後,var追隨者...在形式.. – user2866746
你確定LINQ to Twitter支持'async'嗎? –