我正在尝试使用DownloadStringAsync方法中的数据制作实时图块。
protected override void OnInvoke(ScheduledTask task){
WebClient web = new WebClient();
web.DownloadStringAsync(new Uri("website"));
web.DownloadStringCompleted += web_DownloadStringCompleted;
StandardTileData data = new StandardTileData();
ShellTile tile = ShellTile.ActiveTiles.First();
data.BackContent = string;
tile.Update(data);
}
void web_DownloadStringCompleted(object sender,
DownloadStringCompletedEventArgs e)
{
string=e.result ;
} // example
string始终返回null。我认为这是因为异步操作。不知何故,如果我可以让它同步也许它可以工作。有任何想法吗 ?感谢
答案 0 :(得分:3)
您有Race Condition由于下载操作是异步的,因此'字符串'当你读取它的值来设置BackContent时,不需要更新变量(不应该编译BTW)。
使用Async/Await关键字尝试此操作:
protected async override void OnInvoke(ScheduledTask task)
{
var web = new Webclient();
var result = await web.DownloadStringTaskAsync(new Uri("website"));
StandardTileData data = new StandardTileData();
ShellTile tile = ShellTile.ActiveTiles.First();
data.BackContent = result;
tile.Update(data);
}
如果您无法在WP8应用中使用DownloadStringTaskAsync,请尝试使用TaskCompletionSource完成相同的操作,例如post中的示例。
protected async override void OnInvoke(ScheduledTask task)
{
var result = await DownloadStringTaskAsync (new Uri("website"));
StandardTileData data = new StandardTileData();
ShellTile tile = ShellTile.ActiveTiles.First();
data.BackContent = result;
tile.Update(data);
}
public Task<string> DownloadStringTaskAsync(Uri address)
{
var tcs = new TaskCompletionSource<string>();
var client = new WebClient();
client.DownloadStringCompleted += (s, e) =>
{
if (e.Error == null)
{
tcs.SetResult(e.Result);
}
else
{
tcs.SetException(e.Error);
}
};
client.DownloadStringAsync(address);
return tcs.Task;
}
以下是example 1&amp; example 2&amp; example 3 from MSDN用于在Windows Phone 8中将Async / Await关键字与WebClient一起使用。
由于您使用的是WP8,因此您可能需要为Async / Await关键字添加Nuget包。跑吧
install-package Microsoft.Bcl.Async
在Package Manager控制台中。或者使用Nuget GUI下载它(搜索&#39; async&#39;)