View Single Post
  #4 (permalink)  
Old April 12th, 2007, 01:42 PM
planoie's Avatar
planoie planoie is offline
Friend of Wrox
Points: 16,481, Level: 55
Points: 16,481, Level: 55 Points: 16,481, Level: 55 Points: 16,481, Level: 55
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
Join Date: Aug 2003
Location: Clifton Park, New York, USA.
Posts: 5,407
Thanks: 0
Thanked 16 Times in 16 Posts

Maybe I can explain with an analogy:

Imagine your program is a lunch Diner. The key players (and what they relate to in your program):

Cook (the form running in the main program thread): makes the food (updates the UI)
Waiter (background worker thread): takes customer's orders (runs your continuous task)

The window to the kitchen is the thread boundary.

Cook spawns off Waiters. The waiters go around doing their tasks in the dining room. When a waiter gets an order, he write it down (prepares data for UI update) and goes to the window. The waiter calls to Cook "Hey Cook! Make this order, here it is." and hands the order ticket thru the window (crossing the boundary).

In your code, the Cook is the main form (running in the parent thread) so your code looks like this:

this.BeginInvoke(new delegate(StartCooking), new object[] {Order});

To map the Diner scenario to the code:

Hey Cook! -> this
Make -> .BeginInvoke( )
this order, -> new delegate(StartCooking)
here it is. -> new object[] {Order}

BeginInvoke will call the "StartCooking" method and pass it the "Order". The ACTUAL call to "StartCooking" is made by an object in the parent thread, versus the object in the child thread that called "BeginInvoke".

In your code, "StartCooking" will be "UpdateUI". Your worker process will invoke it with the necessary information to update the UI controls. However, the call will actually be made from the main thread which permits control updates.

I hope this helps explain how it works. I have a program that does this, but it would take a while to extract all the non-important code from the relevant stuff to show you. However, I got it from an article somewhere, so you should be able to find something similar.

Reply With Quote