在另一个线程上运行时"Object reference not set to an instance of an object"



我正试图从一个静态类(称为TitterHandler)中使用TweetSharp,因此理论上我稍后可以将其交换。

该示例建议使用Dispatch.BeginInvoke,以便在更新UI时使用UI线程完成。

我只想将数据加载到模型中,尽管无可否认,这将触发一个OnPropertyChanged事件,该事件将更新UI。由于这是一个静态方法,所以我使用System.Windows.Deployment.Current.Dispatcher.BeginInvoke

然而,它不断崩溃,并出现"Object not set to a reference"异常。我对线程的理解相当有限,但从我收集的来看

  • UI线程需要更新UI,但主线程可能会触发一个事件,然后由UI线程获取-为了测试这一点,我将其分配给一个与UI完全分离的静态变量(TweetCache),但应用程序仍然崩溃
  • 如果没有对线程的引用,线程可能会被垃圾回收。我在类上放置了一个引用(Thread),但它仍然崩溃

我没有主意了,这是代码。。。

public class TwitterHandler
{
public static TwitterService Service = new TwitterService(AppConfig.TwitterConsumerKey, AppConfig.TwitterConsumerSecret);
internal static void LoadTweetsFromWeb()
{
TwitterHandler.Service.AuthenticateWith(AppConfig.TwitterToken, AppConfig.TwitterTokenSecret);
TwitterHandler.Service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions() 
{ ScreenName = AppConfig.NewsBrandingTwitterHandle, }, 
TwitterHandler.OnTweetsLoaded);
}

// Put this here to maintain a refrence to the thread to avoid GC
public static DispatcherOperation Thread;
// A 'thread external' reference with no onward events that trigger UI changes
public static List<Tweet> TweetCache;
public static void OnTweetsLoaded(IEnumerable<TwitterStatus> statuses, TwitterResponse res)
{
if (res.StatusCode == HttpStatusCode.OK)
{
TwitterHandler.Thread = System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
List<Tweet> tweets = new List<Tweet>();
foreach (TwitterStatus status in statuses)
{
tweets.Add(new Tweet()
{
Content = status.Text,
UrlString = status.Place.Url,
});
}
if (tweets.Count > 0)
{
// App.Tweets = tweets;
// TweetCache raises no 'PropertyChanged' event
TwitterHandler.TweetCache = tweets;
}
});
}

}


}

我们共享的调试能力显示status.Place为空。

(其他选项可能是,但可能性较小:调用者处置statuses成员)

相关内容

最新更新