开发者

asynchronous operation/tasks in WP7/Silverlight

When the app lo开发者_C百科ads I would like to read a local resource file parse it and populate the data structure and then the UI. I would like this happen in non-UI thread and how do I achieve this ? The file is in Json format and I am using json.net library to deserialize it. When I tested this even the progress bar is not displayed for this duration and I tried using the toolkit:performanceprogressbar and even that does not show me the progress bar so I am wondering what would be the right solution.

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); 


The class you need is the BackgroundwWorker class. You use it like this:-

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();

BTW, are you sure you can't use the DataContractJsonSerializer? The fact that you feel the need to do this in an async manner would suggest that the data is sizable and memory is at a premium on WP7. The JSON.NET approach requires that you read the entire JSON stream into a string before you deserialise it whereas the DataContractJsonSerializer can deserializer directly off a stream.


  1. Start the performance progress bar displaying by setting IsIndeterminate to true
  2. Get and load your resources using a background worker thread
  3. You can only update the UI on the UI thread
  4. When all done set IsIndeterminate to False
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜