0

I am working on an application which has 4 panels. The first panel displays static images, the second however loads a webpage. Since I will be navigating sequentially, I want to load the web page in the second panel before I actually visit it. How to implement it? It is not possible using a new thread or background worker since they won't be thread safe. Is there a better way to do it? How to load the webpage without freezing my UI and is it possible to load it before I actually visit it as I said?

Niranjan Sonachalam
  • 1,545
  • 1
  • 20
  • 29
  • "since they won't be thread safe" - what won't be thread safe? Your question is unclear. – Jon Skeet Aug 18 '12 at 12:02
  • @Niranjan You can load the web page on a background thread, you just cannot access the UI control directly from that same background thread, you must manipulate the control from the thread that owns the control. – slugster Aug 18 '12 at 12:13
  • @Slugster : Can you explain this a bit, am a newbie – Niranjan Sonachalam Aug 18 '12 at 12:14
  • Controls are created on threads (usually "the UI thread" that you hear people talking about, but not always - controls can be created on background threads too, not that you normally would). Your question should actually be *"how do I marshal data between two threads"* (so that you can download in background thread, then beck in the thread that owns the UI control you know the operation has finished and you can use the data). – slugster Aug 18 '12 at 12:20

2 Answers2

2

You have no options here, the WebBrowser class is fundamentally thread-unsafe and has a hard thread affinity. There are ways to run it on a separate thread, this answer shows you how. But as long as you also need it to render the page content on your UI then you must write code that's asynchronous. Whatever you do must be implemented in the DocumentCompleted event handler. A simple state machine can do wonders.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
-1

Dispatcher.BeginInvoke(the_method_loading_the_page)

Should fix it.

mihaiconst
  • 88
  • 1
  • 7
  • -1 for not 1) checking which UI type the OP is using (WPF/Silverlight/Winforms), and 2) mentioning a whole bunch of detail that should be mentioned about the dispatcher. – slugster Aug 18 '12 at 12:09