What's The Deal With Multi-Threading And Background Workers In WPF

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 3509 Views - Last Post: 10 January 2014 - 10:28 AM Rate Topic: -----

#1 adn258  Icon User is offline

  • D.I.C Addict

Reputation: 12
  • View blog
  • Posts: 816
  • Joined: 31-August 11

What's The Deal With Multi-Threading And Background Workers In WPF

Posted 26 December 2013 - 03:21 PM

So one of the things I've loved to use if Background Workers and then even launching parallel threads from a background worker (sometimes) so the UI thread isn't tied up at all, but that was back in WinForms.

Multi-Threading technologies and parallelism seem to be a different bag in WPF. What's the deal guys? How do parallel threads work in WPF? Also I was reading somewhere that WPF uses Parralel threads BY ITSELF a lot of items in applications when it's needed. Is this true? What should I know about this?

Is This A Good Question/Topic? 0
  • +

Replies To: What's The Deal With Multi-Threading And Background Workers In WPF

#2 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 13397
  • View blog
  • Posts: 53,465
  • Joined: 12-June 08

Re: What's The Deal With Multi-Threading And Background Workers In WPF

Posted 26 December 2013 - 04:28 PM

Have you read these pages?

Threading Model
Build More Responsive Apps With The Dispatcher
Was This Post Helpful? 0
  • +
  • -

#3 adn258  Icon User is offline

  • D.I.C Addict

Reputation: 12
  • View blog
  • Posts: 816
  • Joined: 31-August 11

Re: What's The Deal With Multi-Threading And Background Workers In WPF

Posted 26 December 2013 - 07:39 PM

Well to be honest no and I apologize I didn't even know what a dispatcher was (or that it existed) again I'm very new to WPF, but I appreciate your linking me to these pages.

So it seems (correct me if I'm wrong) according to MSN that WPF apps run in just 2 threads automatically? One for the UI and one for processing information right? This is superior right from the get-go from WinForms which (correct me if I'm wrong) started out with 1 THREAD for both the UI and DataProcessing at the same time?

So in a certain sense when you open a WPF app you automatically have 1 background worker or background thread working for you is that right?
Was This Post Helpful? 0
  • +
  • -

#4 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 1003
  • View blog
  • Posts: 975
  • Joined: 30-September 10

Re: What's The Deal With Multi-Threading And Background Workers In WPF

Posted 27 December 2013 - 06:12 AM

*
POPULAR

WPF does start out with 2 threads - a render thread and a UI thread - yes. However, the render thread has a very specific, fixed job.

Very briefly, there are essentially two subsystems in WPF that we are concerned about here - the visual system and the composition system.

The visual system runs on the UI thread where user input is gathered, events are handled, your code is run etc. This is reasonably familiar (from a high level) from WinForms.

The composition system runs on the render thread, below the visual system, and is responsible for initiating low level rendering of visual elements and often the animation of elements too Edit: Not sure this is actually true in WPF at the moment.

The rendering process

Essentially, what happens is when the visual system needs to render the UI (i.e. when a visual change is made to the UI), it (running on the UI thread) sends the visual changes to the composition system (running on the render thread). At this point, the UI thread is done with the rendering process, and can do other things.

The composition system now performs various preprocessing like building a tree of visual elements to be rendered, calculating pixels etc.

The composition system then passes all this data to the rendering engine, which does some low level preprocessing of its own like tessellating shapes etc, and it then passes everything to Direct X which interacts with the display driver.

Finally, the display driver interacts with the graphics card to performs the rendering of the graphics to the screen using the graphics card.


Impact of the render thread on application level multithreading

So, while it is true that the WPF system does separate the rendering process off onto a background thread, this is really a system facility. The render thread has a dedicated purpose in life, and while it potentially brings improvements over the WinForms system, it won't really help you directly in your day to day application level needs.

For example, if you are loading some large file off disk, your UI will freeze (just like in WinForms) if you don't take measures to keep the UI thread free (whether that be via asynchronous IO or using a dedicated background thread). The UI thread still deals with user input and such like, so if you are blocking that thread, your user will see a frozen application. There is no magic here that will automatically keep your UI responsive for you :)

WPF vs Winforms

Really, you can forget about the render thread, since it won't really help you in your day to day multithreading needs. It will happily continue working away in the background doing its thing without you having to think about it.

So, that leaves you with a single UI thread by default, just like WinForms. Really, WPF isn't that different in terms of its threading model from the application developer's perspective. Sure, it has some nice advancements (like dispatcher priorities, for example), but ultimately:

  • The UI thread is still running a message loop.
  • Controls should only be accessed from the UI thread
  • You still have Invoke() and BeginInvoke() which serve the same purpose as the WinForm equivalents.
  • You still have the BackgroundWorker class and all the other threading/asynchronous mechanisms, all of which continue to work fine in WPF.

This post has been edited by CodingSup3rnatur@l-360: 27 December 2013 - 01:15 PM
Reason for edit:: Calrification on animation and render thread + typo

Was This Post Helpful? 9
  • +
  • -

#5 adn258  Icon User is offline

  • D.I.C Addict

Reputation: 12
  • View blog
  • Posts: 816
  • Joined: 31-August 11

Re: What's The Deal With Multi-Threading And Background Workers In WPF

Posted 27 December 2013 - 07:23 PM

Thank you so much supernatural. So another way if you don't want to have to use ANY additional threads like a background worker is to simply use DispatcherPriority and use dispatch right?


So Correct me if I'm wrong but using a dispatcher CAN keep your UI from freezing during long operations since User interaction with the UI will start taking priority in UI thread based stuff FIRST before continuing calculations or operations that have nothing to do with the UI.

Is that right?

This post has been edited by adn258: 27 December 2013 - 07:25 PM

Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq  Icon User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6504
  • View blog
  • Posts: 14,355
  • Joined: 02-June 10

Re: What's The Deal With Multi-Threading And Background Workers In WPF

Posted 27 December 2013 - 08:05 PM

View PostCodingSup3rnatur@l-360, on 27 December 2013 - 07:12 AM, said:

WPF does start out with 2 threads - a render thread and a UI thread - yes. However, the render thread has a very specific, fixed job. [...]


Dude, really nice. I'd nudge you into formalizing that into a tutorial in the WPF section to go along with the other "WPF for WinForms developers" tutorials. It would be nice to see a collection of them covering the areas converts from WinForms tend to trip over.
Was This Post Helpful? 0
  • +
  • -

#7 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 1003
  • View blog
  • Posts: 975
  • Joined: 30-September 10

Re: What's The Deal With Multi-Threading And Background Workers In WPF

Posted 28 December 2013 - 06:41 AM

Quote

So another way if you don't want to have to use ANY additional threads like a background worker is to simply use DispatcherPriority and use dispatch right? ... Using a dispatcher CAN keep your UI from freezing during long operations since User interaction with the UI will start taking priority in UI thread


To a limited extent, yes. However, if you are going to rely on dispatcher priorities and Dispatcher.BeginInvoke() alone to keep the UI responsive during a long running operation, you need to break up the long running task into very small units, none of which are large enough to noticeably freeze the UI when executed. This often isn't going to be desirable, practical, or even possible to do.

Take a look at this really simple example that hopefully illustrates that dispatcher priorities definitely aren't a replacement for additional threads or traditional asynchronous programming techniques:

Spoiler


Now, when the 'Read' button is clicked, ReadAll() might not be be executed immediately if the application is busy doing something else, due to the ApplicationIdle priority I've used. However, when the time does come to execute ReadAll(), the application will still freeze until it completes, because it is all happening on the UI thread.

You have to remember that the priorities only govern when your work item passed to Dispatcher.BeginInvoke() is allowed to start executing. Once your work item has started executing, it will run to completion without interruption by other work items (blocking the UI thread as it goes), regardless of the priorities involved.

So, the BackgroundWorker class, the Task Parallel Library, the async/await mechanism and other familiar APIs are still very relevant in WPF, and you'll probably be relying on them far more than dispatcher priorities, because they are simple to use, have built-in support for things like progress reporting and cancellation, will work for almost any long running operation you can throw at them, and, ultimately, will be more reliable in keeping the UI responsive.


Quote

I'd nudge you into formalizing that into a tutorial in the WPF section to go along with the other "WPF for WinForms developers" tutorials


Yeah, I'll give that a go :)

This post has been edited by CodingSup3rnatur@l-360: 28 December 2013 - 07:55 AM
Reason for edit:: Typo in code

Was This Post Helpful? 3
  • +
  • -

#8 adn258  Icon User is offline

  • D.I.C Addict

Reputation: 12
  • View blog
  • Posts: 816
  • Joined: 31-August 11

Re: What's The Deal With Multi-Threading And Background Workers In WPF

Posted 29 December 2013 - 03:14 PM

Thank you so much Coding Supernatural. It's good to know that the Background Worker is still relevant. I have one more question related to threads though but nothing to do with using anything in WPF.

So when you use a background thread it's still using just ONE thread correct me if I'm wrong to carry out a calculation or operation. Okay but in C# of course you can use multitasking technologies like parallel foreach and parallel invoke.

Okay when you use these options on machines like mine which has an i7 processor this doesn't necessarily mean the calculations will go faster does it?

See I've seen a lot of confusion on forums etc. that basically state when you use multithreading like that you're gaining more Gigahertz processing calculation power etc. Correct me if I'm wrong but this isn't true?

Essentially in one sense using 1 thread for a long calculation generally calculates things just as fast from a sheer processing in Gigahertz clock speed etc. as using parallel threads. Can you explain this whole phenomenon?
Was This Post Helpful? 0
  • +
  • -

#9 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5101
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: What's The Deal With Multi-Threading And Background Workers In WPF

Posted 30 December 2013 - 09:47 AM

View PostCodingSup3rnatur@l-360, on 28 December 2013 - 07:41 AM, said:

Quote

I'd nudge you into formalizing that into a tutorial in the WPF section to go along with the other "WPF for WinForms developers" tutorials


Yeah, I'll give that a go :)/>


PM me when you do so; I'll add it to the resources and the Learning C# series thread.
Was This Post Helpful? 0
  • +
  • -

#10 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 1003
  • View blog
  • Posts: 975
  • Joined: 30-September 10

Re: What's The Deal With Multi-Threading And Background Workers In WPF

Posted 31 December 2013 - 03:38 PM

Quote

So when you use a background thread it's still using just ONE thread correct me if I'm wrong to carry out a calculation or operation.


If you start one extra thread, then only one extra thread will be used, yes. If you meant to say background worker, rather than background thread, then your statement is still correct. The BackgroundWorker class grabs one thread from the thread pool, and executes your work on that thread.

Quote

Okay when you use these options on machines like mine which has an i7 processor this doesn't necessarily mean the calculations will go faster does it?


True. Parallelizing a section of code won't necessarily mean that it will complete faster. Whether or not you see any speed increases, and the extent of any speed increase, will depend on a wide range of factors. Some key factors often include:

  • The ratio of the number of I/O bound operations to the number of CPU bound operations in the code you are parallelizing.
  • The amount of work the threads have to perform vs the cost of partitioning the work across the threads, and managing the threads at runtime.
  • The amount of contention for shared data/resources that is present between threads.
  • The number of processor cores you have vs the number of threads you are using.


Basically, when using multiple threads to improve the performance of your code, the only sane advice is to experiment, and let performance measurements guide you towards the best configuration.

Quote

See I've seen a lot of confusion on forums etc. that basically state when you use multithreading like that you're gaining more Gigahertz processing calculation power etc. Correct me if I'm wrong but this isn't true?
...
Essentially in one sense using 1 thread for a long calculation generally calculates things just as fast from a sheer processing in Gigahertz clock speed etc. as using parallel threads. Can you explain this whole phenomenon?


Generally, when you use multiple threads as a means of improving the speed of your code, you are trying to use the available processing resources more efficiently, and ensure your code can continue to do this in the event that extra processing resources become available.

Now, the clock speed of a CPU will not be increased by using multiple threads. Using multiple threads won't magically make your hardware faster. However, using multiple threads can help you make better use of the hardware you have. Primarily, it can increase CPU utilization, thereby increasing the number of instructions executed per unit time (a measure of throughput).

For example, if you have N cores and your code is purely CPU bound, you could theoretically improve the speed of your code by a factor of N. This is because each core can execute instructions simultaneously, so by using all cores, you can theoretically increase the throughput by a factor of N.

Furthermore, a similar idea can apply to single core machines. For example, if you have a single core machine, and two threads, if one thread gets blocked after an I/O request, the other thread can still potentially continue working; making use of an otherwise idle CPU. This could once again lead to increases in throughput over using only one thread.

In both these examples, the hardware hasn't got faster; we are just making better, more efficient use of the hardware.

This post has been edited by CodingSup3rnatur@l-360: 31 December 2013 - 04:01 PM

Was This Post Helpful? 4
  • +
  • -

#11 adn258  Icon User is offline

  • D.I.C Addict

Reputation: 12
  • View blog
  • Posts: 816
  • Joined: 31-August 11

Re: What's The Deal With Multi-Threading And Background Workers In WPF

Posted 07 January 2014 - 12:17 PM

Supernatural I just wanted to say that was a beautiful answer to this question. Thank you very much!! I finally understand that now!
Was This Post Helpful? 0
  • +
  • -

#12 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon

Reputation: 2298
  • View blog
  • Posts: 9,535
  • Joined: 29-May 08

Re: What's The Deal With Multi-Threading And Background Workers In WPF

Posted 10 January 2014 - 12:36 AM

T'd prefer to us Task rather than Threads, since those Task can automatically be spread out and managed across the available Threads in the TaskPool. it also allows me to use asynchronousity so I don't tie up a thread waiting for IO bound content to return. When the data is returned "Call Me Back" then continue with the next section of code.

This in turn makes the Users experience more fluid and responsive. I can't let the user continue to do stuff, and not break their flow by blocking the UI.

For example the Win8 App (Metro) Store applications aren't permitted to have synchronous blocking calls. They have to be Asynchronous and non blocking.
Was This Post Helpful? 0
  • +
  • -

#13 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5101
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: What's The Deal With Multi-Threading And Background Workers In WPF

Posted 10 January 2014 - 08:05 AM

Quote

For example the Win8 App (Metro) Store applications aren't permitted to have synchronous blocking calls. They have to be Asynchronous and non blocking.


Just like Silverlight before it. Unfortunately for it, they didn't have the async/await keywords yet, so dealing with asynchronous programming in Silverlight was more of a pain.
Was This Post Helpful? 0
  • +
  • -

#14 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 5824
  • View blog
  • Posts: 19,835
  • Joined: 05-May 12

Re: What's The Deal With Multi-Threading And Background Workers In WPF

Posted 10 January 2014 - 08:30 AM

And a lot of boiler plate code to implement the asynchronous pattern.
Was This Post Helpful? 0
  • +
  • -

#15 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon

Reputation: 2298
  • View blog
  • Posts: 9,535
  • Joined: 29-May 08

Re: What's The Deal With Multi-Threading And Background Workers In WPF

Posted 10 January 2014 - 10:08 AM

You can use Async and Await in Silverlight 4 and 5. You just need to install the Targeting Pack

http://10rem.net/blo...-targeting-pack

This post has been edited by AdamSpeight2008: 10 January 2014 - 10:10 AM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2