跨线程未授权访问异常MainViewModel->;async LoadData()

本文关键字:gt async LoadData MainViewModel- 线程 授权 访问 异常 | 更新日期: 2023-09-27 18:29:21


使用Windows Phone 8C#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#)中的无效跨线程访问

由于您使用的是await,因此根本不需要UIThread。只需删除所有ConfigureAwait(false)调用。

跨线程未授权访问异常MainViewModel->;async LoadData()