我正在尝试制作活瓷砖,它使用来自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字符串一直在返回null。我认为这是因为异步操作。不知怎么的,如果我能让它同步,也许它可以工作。有什么想法吗?谢谢
发布于 2014-06-25 15:58:40
您有一个种族条件,因为下载操作是异步的,所以在读取它的值以设置BackContent时,不必更新“string”变量(不应该编译BTW)。
用异步/等待关键字试试:
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);
}如果您不能在您的DownloadStringTaskAsync应用程序中使用WP8,那么尝试使用TaskCompletionSource来完成相同的任务,例如在这个帖子中。
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;
}下面是一个例1 & 例2 & 示例3来自MSDN,用于在Windows 8中使用带有WebClient的异步/等待关键字。
由于您使用的是WP8,所以可能需要为异步/等待关键字添加Nuget包。快跑
安装包Microsoft.Bcl.Async
在包管理器控制台中。或者使用Nuget GUI下载(搜索‘异步’)
https://stackoverflow.com/questions/24413269
复制相似问题