使用Windows Phone 8、C#和RestSharp。
从 RadDiagnostics 获取有关错误的信息:
[Type]:[UnauthorizedAccessException]
[ExceptionMessage]:[Invalid cross-thread access.]
[StackTrace]:[
at MS.Internal.XcpImports.CheckThread()
at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value, Boolean allowReadOnlySet)
at System.Windows.DependencyObject.SetValue(DependencyProperty property, Boolean b)
at Microsoft.Phone.Shell.ProgressIndicator.set_IsIndeterminate(Boolean value)
at RWJ.Misc.GlobalLoading.NotifyValueChanged()
at RWJ.Misc.GlobalLoading.set_IsLoading(Boolean value)
at RWJ.ViewModels.MainViewModel.ExecuteAsync[T](RestRequest request, String host)
at RWJ.ViewModels.MainViewModel.<LoadData>d__a.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__0(Object state)]
示例代码:
public async void LoadData()
{
// authenticate application
string Authentication = EncodeTo64(ConsumerKey + ":" + ConsumerSecret);
RestClient twitterClient = new RestClient("https://api.twitter.com");
IRestResponse resp = null;
OAuthToken token = null;
RestRequest tweetReq = new RestRequest("oauth2/token", Method.POST);
tweetReq.AddHeader("Authorization", "Basic " + Authentication);
tweetReq.AddHeader("Host", "api.twitter.com");
tweetReq.AddHeader("User-Agent", "[APP NAME]");
tweetReq.AddHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF8");
tweetReq.AddParameter("grant_type", "client_credentials");
try
{
resp = await twitterClient.GetResponseAsync(tweetReq);
token = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuthToken>(resp.Content);
}
catch (Exception ex)
{
// error handling
}
// fetch tweets
twitterClient.BaseUrl = tapi;
tweetReq = new RestRequest("search/tweets.json", Method.GET);
tweetReq.AddHeader("Authorization", "Bearer " + token.access_token);
tweetReq.AddHeader("Accept-Encoding", "gzip");
tweetReq.AddParameter("q", "from:twitterapi exclude:retweets exclude:replies");
tweetReq.AddParameter("count", "10");
string[] _createdAt = new string[10];
string[] _text = new string[10];
string[] _link = new string[10];
string[] _image = new string[10];
Peep res = await ExecuteAsync<Peep>(tweetReq, tapi).ConfigureAwait(false);
Status[] statuses = res.statuses;
int i = 0;
foreach (Status tweet in statuses)
{
_createdAt[i] = tweet.created_at;
_text[i] = tweet.text;
if (tweet.entities.urls.Length > 0) { _link[i] = tweet.entities.urls[0].expanded_url; } else { _link[i] = ""; }
if (tweet.entities.media != null) { _image[i] = tweet.entities.media[0].media_url; } else { _image[i] = ""; }
i++;
}
for (int x = 0; x < i; x++)
{
if (_link[x].Contains("youtube.com") || _link[x].Contains("youtu.be"))
{
Regex YT = new Regex(@"youtu(?:\.be|be\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)");
Match youTube = YT.Match(_link[x]);
if (youTube.Success)
{
_linkType[x] = "youtube";
_link[x] = youTube.Groups[1].Value;
}
else { _linkType[x] = "url"; }
}
else if (_link[x].Contains("instagram.com") || _link[x].Contains("instagr.am"))
{
RestRequest iReq = new RestRequest();
iReq.AddParameter("url", _link[x]);
Instagram inst = await ExecuteAsync<Instagram>(iReq, instaapi).ConfigureAwait(false);
_linkType[x] = "url";
_image[x] = inst.url;
}
else if (_link[x].Contains("http://t.co/"))
{
//do nothing, image url should already be loaded in _image[x]
}
UIThread.Invoke(() =>
{
// this is where I get Cross Thread Operation not valid
this.Twitter.Add(new TweetViewModel() { Date = _createdAt[x], Tweet = _text[x], Link = _link[x], LinkType = _linkType[x], Image = _image[x] });
});
}
}
这段代码完美无瑕,直到它应该将项目添加到集合中。
这就是引发异常的地方。
该类UIThread
来自此处:UnauthorizedAccessException:Silverlight 应用程序中的无效跨线程访问(XAML/C#)