我正在尝试使用周期性任务代理在shell磁贴上显示我的顶级推文。瓷砖必须每30分钟更新一次。使用任务并行库是为了连续。问题是我得到了“无效的交叉线程访问”例外。
这是我的Schedule Task Agent代码:
protected override void OnInvoke(ScheduledTask task)
{
ShellToast popupMessage = new ShellToast()
{
Title = "My First Agent",
Content = "Background Task Launched",
};
popupMessage.Show();
UpdateTile().ContinueWith(x => NotifyComplete());
}
private Task<bool> UpdateTile()
{
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.AttachedToParent);
WebClient twitter = new WebClient();
twitter.DownloadStringCompleted += (sender, e) =>
{
if (e.Error != null)
{
tcs.TrySetResult(true);
}
else
{
XElement xmlTweets = XElement.Parse(e.Result);
var message2 = xmlTweets.Descendants("status")
.Select(x => x.Element("text").Value).FirstOrDefault();
ShellTile appTile = ShellTile.ActiveTiles.First();
if (appTile != null)
{
StandardTileData tileData = new StandardTileData
{
BackContent = DateTime.Now.ToString() + message2.ToString()
};
appTile.Update(tileData);
tcs.TrySetResult(true);
}
else
{
tcs.TrySetResult(true);
}
}
};
twitter.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=dnivra26"));
return tcs.Task;
}
这是抛出异常的行:
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.AttachedToParent);
//这就是我所做的改变和
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
ShellTile appTile = ShellTile.ActiveTiles.First();
if (appTile != null)
{
StandardTileData tileData = new StandardTileData
{
BackContent = DateTime.Now.ToString() + message2.ToString()
};
appTile.Update(tileData);
tcs.TrySetResult(true);
}
else
{
tcs.TrySetResult(true);
}
});
这就是线外显示:
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.AttachedToParent);
答案 0 :(得分:4)
由于工作是在后台线程上完成的,因此无法在同一线程上更新UI。相反,在更新UI的部分使用Deployment.Current.Dispatcher.BeginInvoke()
。
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
ShellTile appTile = ShellTile.ActiveTiles.First();
if (appTile != null)
{
StandardTileData tileData = new StandardTileData
{
BackContent = DateTime.Now.ToString() + message2.ToString()
};
appTile.Update(tileData);
tcs.TrySetResult(true);
}
else
{
tcs.TrySetResult(true);
}
}