开发者

BackgroundWorker: Does every method called from the DoWorkEventHandler run in the background thread?

开发者 https://www.devze.com 2023-02-08 07:05 出处:网络
I have a MVVM application which loads data via a XML on a server. The XML is downloaded with WebClient.DownloadStringAsync() and then is parsed by a method. The problem is that the XML is kind of big

I have a MVVM application which loads data via a XML on a server. The XML is downloaded with WebClient.DownloadStringAsync() and then is parsed by a method. The problem is that the XML is kind of big so the UI freezes for a while (2-3 seconds or so), while the XML is parsing.

My idea to solve this problem was to use a BackgroundWorker to h开发者_开发问答andle the parsing. But does every method called from my DoWorkEventHandler run in the background thread? Even the webclients event handlers?

The whole parsing thing takes place in a DownloadStringCompletedEventHandler so it would be kind of useless if that didn't run in a background thread.

Thanks for you help, Stack Overflow has been amazing so far :) Keep it up!


You need to be careful when using Event-based Asynchronous Pattern (EAP) components from a BackgroundWorker. In particular, if they are created and started by the BackgroundWorker.DoWork method, then they will raise their events on ThreadPool threads rather than the UI thread. An MSDN article published yesterday has an illustration of this situation and an explanation of why this happens.

If you call WebClient.DownloadStringAsync from BackgroundWorker.DoWork (which is running on a ThreadPool thread), then DownloadStringCompletedEventHandler will run on a ThreadPool thread. However, this may be a different thread than the BackgroundWorker thread; and the BackgroundWorker may have completed already by the time that DownloadStringCompletedEventHandler starts.

So, I wouldn't say that it runs "within" the BackgroundWorker. Rather, it's acting in a free-threaded style. The event will fire on a ThreadPool thread which may or may not be the same as the BackgroundWorker thread, and the BackgroundWorker may or may not be complete when the event fires.

I think a better solution may be to keep the WebClient owned by the UI thread, and have its event handler kick off a BackgroundWorker. That way, both EAP components are owned by the UI thread and will behave as expected.


yes, it all runs in the bgworker. But you have to be carefull. If you update properties which are bound to the view and you update them in your bgworker (and of course NotifyPropertyChanged is raised) there will be an exception! (Cause you want to get data from another thread in your UI Thread).


Yes as far as I understood, DoWorkEventHandler fires in a separate thread. Also check out ThreadPool.QueueWorkItem etc which might be a simpler process for you.

0

精彩评论

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