我今天一直在試驗WP7應用程序,並且遇到了一些困難。 我喜歡在用戶界面和主應用程序代碼之間分開,但是我撞到了牆上。WP7中的異步調用
我成功實現了一個webclient請求並得到了一個結果,但因爲調用是異步的,我不知道如何將這個備份傳遞給UI級別。我似乎無法等待響應完成或任何事情。 我一定在做錯事。
(這是xbox360Voice庫,我有下載在我的網站:http://www.jamesstuddart.co.uk/Projects/ASP.Net/Xbox_Feeds/這我移植到WP7作爲測試)
這裏是後端代碼片段:
internal const string BaseUrlFormat = "http://www.360voice.com/api/gamertag-profile.asp?tag={0}";
internal static string ResponseXml { get; set; }
internal static WebClient Client = new WebClient();
public static XboxGamer? GetGamer(string gamerTag)
{
var url = string.Format(BaseUrlFormat, gamerTag);
var response = GetResponse(url, null, null);
return SerializeResponse(response);
}
internal static XboxGamer? SerializeResponse(string response)
{
if (string.IsNullOrEmpty(response))
{
return null;
}
var tempGamer = new XboxGamer();
var gamer = (XboxGamer)SerializationMethods.Deserialize(tempGamer, response);
return gamer;
}
internal static string GetResponse(string url, string userName, string password)
{
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
{
Client.Credentials = new NetworkCredential(userName, password);
}
try
{
Client.DownloadStringCompleted += ClientDownloadStringCompleted;
Client.DownloadStringAsync(new Uri(url));
return ResponseXml;
}
catch (Exception ex)
{
return null;
}
}
internal static void ClientDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
ResponseXml = e.Result;
}
}
這是前端代碼:
public void GetGamerDetails()
{
var xboxManager = XboxFactory.GetXboxManager("DarkV1p3r");
var xboxGamer = xboxManager.GetGamer();
if (xboxGamer.HasValue)
{
var profile = xboxGamer.Value.Profile[0];
imgAvatar.Source = new BitmapImage(new Uri(profile.ProfilePictureMiniUrl));
txtUserName.Text = profile.GamerTag;
txtGamerScore.Text = int.Parse(profile.GamerScore).ToString("G 0,000");
txtZone.Text = profile.PlayerZone;
}
else
{
txtUserName.Text = "Failed to load data";
}
}
現在我明白我需要把東西ClientDownloadStringCompleted
,但我不確定是什麼。
「正如你所看到的,異步編程可能會變得雜亂無章。」 ...這是使用F#的一個原因。藉助F#,您可以將代碼重構爲異步,而無需執行所有的回調 - 反轉控制翻轉。 – Brian 2010-10-02 20:29:24
@Brian:我完全同意。我只是希望函數式編程能夠變得更容易理解,這可能是年輕人的頭腦,但不管我多麼努力,我都無法理解我的概念。 – AnthonyWJones 2010-10-02 20:57:06
生病給了這個去一個明天,謝謝 – JamesStuddart 2010-10-03 00:25:07