当应用程序加载时,我想读取本地资源文件解析它并填充数据结构,然后填充UI。我想在非UI线程中发生这种情况,我该如何实现? 该文件是Json格式,我使用json.net库反序列化它。 当我测试这个时,即使在这段时间内没有显示进度条,我尝试使用工具包:performanceprogressbar,甚至没有向我显示进度条,所以我想知道什么是正确的解决方案。
var resource = System.Windows.Application.GetResourceStream(new Uri(string.Format("testProj;component/{0}", fileName), UriKind.Relative));
StreamReader streamReader = new StreamReader(resource.Stream);
string jsonText = streamReader.ReadToEnd();
jsonList = JsonConvert.DeserializeObject<List<ComicItem>>(jsonText);
答案 0 :(得分:8)
您需要的课程是BackgroundwWorker
课程。你这样使用它: -
var bw = new BackgroundWorker()
bw.DoWork += (s, args) =>
{
// This runs on a background thread.
var resource = System.Windows.Application.GetResourceStream(new Uri(string.Format("testProj;component/{0}", fileName), UriKind.Relative));
StreamReader streamReader = new StreamReader(resource.Stream);
string jsonText = streamReader.ReadToEnd();
jsonList = JsonConvert.DeserializeObject<List<ComicItem>>(jsonText);
// Other stuff with data.
};
bw.RunWorkerCompleted += (s, args) =>
{
// Do your UI work here this will run on the UI thread.
// Clear progress bar.
};
// Set progress bar.
bw.RunWorkerAsync();
顺便说一下,你确定你不能使用DataContractJsonSerializer
吗?您觉得需要以异步方式执行此操作这一事实表明数据相当大且内存在WP7上非常重要。 JSON.NET方法要求您在将其反序列化之前将整个JSON流读取为字符串,而DataContractJsonSerializer可以直接从流中解串。
答案 1 :(得分:0)