我正在嘗試使用週期性任務代理程序在外殼磁貼上顯示我的最新推文。瓷磚必須每30分鐘更新一次。我使用任務並行庫是連續的。問題是,我得到一個「無效的交叉線程訪問」例外。週期性任務中無效的跨線程訪問異常
這是我的計劃任務代理代碼:
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);
請檢查Windows Mobile 7是否不存在:它是Windows Phone 7,它是一個完全不同的操作系統,它不使用Compact Framework。更改您的標題並使用更準確的標籤! ;) – 2012-01-10 15:10:42