Tuesday, August 26, 2008

[Multi-Threading] Syncing between threads by SynchronizationContext

-----------------------------------------
Download source code package for this article:

If you can't see/download the zip file, please try to use TOR. TOR is a great tool that can break the GFW and let you access any website that prohibited by GFW.
http://vidalia-project.net/download.php
-----------------------------------------

I'd like to offer a series of tech articles on Multi-Threading which is a hot topic these days. Actually, I have a tech talk weeks later. So I'm trying to introduce my learning on this topic to our group first :) Please don't hesitate to give me suggestions to improve my knowledge.


Today's topic is syncing between threads by SynchronizationContext.

As you know, from MFC, WinForm to WPF, UI element can't be accessed from a thread other than UI thread. If you try to do this, you will meet an assertion, or exception. For WPF applications, there will be two threads. One is rendering thread, the other is UI thread. Rendering thread is responsible for rendering UI elements to graphics card, while UI thread is for managing UI elements, and do application logic, etc. MSDN says that you can only access UI elements from UI thread. So, how can we delegate a task which will accessing UI element from a background thread? Since we need to update UI while doing background work, reporting progress or the completion of the work. SynchronizationContext can help us.

UI thread works on a work item queue mode. All works queued in a queue. UI thread select a work item which has the highest priority in the queue when the thread finished a work item. Because work items will be executed within UI thread, a big work item can block UI operations. So make work items small enough, don't do heavy work in it. That's why we need a background worker thread.

SynchronizationContext provides Post() and Send(). You can call them from your background thread, and delegate methods passed to them will be executed within UI thread. Delegate method passed to Post() will be executed asynchronously, while to Send(), the caller of Send() will wait until the delegate method returned.

DIG DEEPER: We can imaging the internal work of Post() or Send(), they will obtain the lock of the queue (work item queue) first, then insert the work item to the queue, and then release the lock.

Please find sample code at the end of this article. Firstly, we create a background thread in Window1() which is the initialization method of the application. We use the BeginInvoke() of the delegate type HeavyBackgroundWorkDelegate. The background thread will be created and started. AsyncCallback() is the handler of completion of background thread. Please note, it will be called from the background thread. In HeavyBackgroundWork(), the entry of background thread, we access UI element by synchronizationContext.Post().

From the debug ourput of the application, we can see, AsyncCallback is in the same thread as background, while UI thread is a different thread.

-------------------
UI thread: 10
Background thread: 6
HeavyBackgroundWork finished.
AsyncCallback is called from thread: 6
----------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Diagnostics;

namespace Async_SynchronizationContext
{
///
/// Interaction logic for Window1.xaml
///
public partial class Window1 : Window
{
private delegate void HeavyBackgroundWorkDelegate();
private SynchronizationContext synchronizationContext;

private void HeavyBackgroundWork()
{
Debug.WriteLine("Background thread: " + Thread.CurrentThread.ManagedThreadId);

// To simulate a time-cost work.
Thread.Sleep(1000);

synchronizationContext.Post(new SendOrPostCallback(delegate(object param)
{
// We have to access TextInfo by synchronizationContext, otherwise
// you will meet an exception.
TextInfo.Text = "HeavyBackgroundWork() has been finished.";
}),
null);

Debug.WriteLine("HeavyBackgroundWork finished.");
}

public void AsyncCallback(IAsyncResult ar)
{
// This method will be called from HeavyBackgroundWork thread, not UI thread.
Debug.WriteLine("AsyncCallback is called from thread: " + Thread.CurrentThread.ManagedThreadId);
}

public Window1()
{
InitializeComponent();

synchronizationContext = SynchronizationContext.Current;

Debug.WriteLine("UI thread: " + Thread.CurrentThread.ManagedThreadId);
HeavyBackgroundWorkDelegate backgroundWork = new HeavyBackgroundWorkDelegate(HeavyBackgroundWork);
backgroundWork.BeginInvoke(AsyncCallback, null);
}
}
}

17 comments:

Zhang Yaping said...

Could you please attach the zip package of your demo projects as well?

Unknown said...

Please try to download the package I added to this post. SkyDrive offered by Windows Live looks great!

Anonymous said...

[url=http://kfarbair.com][img]http://www.kfarbair.com/_images/_photos/photo_big8.jpg[/img][/url]

מלון [url=http://www.kfarbair.com]כפר בעיר[/url] - אינטימיות, [url=http://kfarbair.com/services.html]שקט[/url] . אנחנו מספקים שירותי אירוח מיוחדים כמו כן ישנו במקום שירות חדרים הכולל [url=http://www.kfarbair.com/eng/index.html]אחרוחות רומנטיות[/url] במחירים מפתיעים אשר מוגשות ישירות לחדרכם...

לפרטים נוספים נא לפנות לאתר האינטרנט שלנו - [url=http://kfarbair.com]כפר בעיר[/url] [url=http://www.kfarbair.com/contact.html][img]http://www.kfarbair.com/_images/apixel.gif[/img][/url]

Anonymous said...

רציתי לחלוק אותכם בחוויה אותו עברתי אחרי הפיגוע בדולפינריום. במשך חצי שנה לאחר המאורע, הרגשתי רע מאוד, ללא שמחת חיים, עייפה ומדוכדכת. עם טיפולים רפואיים רגילים לא יכולתי לשקם את עצמי ולכן פניתי ל- [b][url=http://www.maker.co.il/3_15707/%D7%9E%D7%90%D7%9E%D7%A8/%D7%9B%D7%9C-%D7%94%D7%A2%D7%95%D7%91%D7%93%D7%95%D7%AA-%D7%A2%D7%9C-%D7%A0%D7%A4%D7%A9-%D7%94%D7%90%D7%93%D7%9D-%D7%95%D7%A2%D7%99%D7%A1%D7%95%D7%99-%D7%A8%D7%A4%D7%95%D7%90%D7%99-(%D7%9E%D7%A1%D7%90%D7%92%60).html]עיסוי[/url][/b] רפואי אלטרנטיבי. המליצו לי על מעסה מקצועי מ-Spa-Vip.co.il - עיסוי עד הבית, אשר מכיל מסאז שוודי מצויין אשר עורר לי את החושים תוך טיפול אחד בלבד. אני לא יכלה להמחיש את השינוי שעברתי, אומנם זה היה טיפול מסאג שוודי ראשוני, השתפר לי המצב הרוח, פיזרתי את השיער ויצאתי מה- [b][url=http://www.academics.co.il/Articles/Article12945.aspx]מסאג[/url][/b]' עם כח מחודש, שמחה ומוכנה להמשך.

עיסוי האיורוודה הוא עיסוי משולב עם מוזיקה נעימה, מוזיקה נעימה וריח של קטורת. בהתחלת העיסוי יש מגע עדין על המגבת לאחר חשיפה של הגוף מכף רגל ועד ראש. מריחת שמן חם מכף רגל ועד הראש, לאחר מכן תנועה מלטפת ועדינה מכף רגל ועד ראש ובחזרה. לאחר כמה תנועות מפנקות מתחיל הטיפול בצידו השני של הגוף, אחרי אותם תנועות על צידו השני ישנו שילוב של לחיצות רפואיות מכיוון שהגוף התרגל למגע מפנק ומרגיע ודבר זה גרם לשרירים להרפות מעט... כל זה בטיפול פרטי של [b][url=http://www.academics.co.il/Authors/Author2173.aspx]מעסה[/url][/b] מקצועי עד בית הלקוח!

אישית לא האמנתי כי דברים כאלה יכולים להיות עד אשר חוויתי מסאז איורוודה באיכות כזאת, המעסה המקצועי הגיע עד לביתי עם מגע כלכך מפנק שלא האמנתי שיכול להיות. אני ממליצה בחום לכל אחד ואחת אשר חשבו על מסאג', עיסוי או סתם פינוק מלטף באירוע אישי על Spa-VIP.co.il.
[img]http://spa-vip.co.il/_images/apixel.gif[/img]

[url=http://spa-vip.co.il/#][img]http://spa-vip.co.il/_images/&%231506%3b&%231497%3b&%231505%3b&%231493%3b&%231497%3b-&%231512%3b&%231508%3b&%231493%3b&%231488%3b&%231497%3b.jpg[/img][/url]

Anonymous said...

Cat Medication Alterna Gel hot news
http://www.performancesporthorses.com/ - klonopin medication
There are studies conducted that those who is suffering from acute epilepsy that is treated by this drug via intravenous administration and 72.
[url=http://www.performancesporthorses.com/]klonopin anxiety[/url]
There are studies conducted that those who is suffering from acute epilepsy that is treated by this drug via intravenous administration and 72.
klonopin anxiety
0 and 2 mg respectively.


http://compositetower.com/ - purchase neurontin
- Do not stop taking Neurontin if you think your condition has improved.
[url=http://compositetower.com/]neurontin gabapentin[/url]
- Consult with your doctor if you suffer from kidney, heart, or liver disease before taking Neurontin.
neurontin gabapentin
Neurontin is prescribed alone or in combination with other medications to treat epileptic seizures in patients above the age of 12.

Anonymous said...

The term [url=http://www.jkahosting.com] web hosting [/url] is elementary, but the mechanics behind it are not.
Web Hosting is a stipulations that was coined to detail the services performed during someone that "hosts" a Net milieu on the Area Wide Web.
You already skilled in that a herd is someone that facilitates an consequence, or a function, like the hostess at a denomination, or an emcee on the present or TV.
In our carton, a "host" involves a computer that is setup to direction the networking and communications indispensable to allow a Web Situation to flaunt custom formatted documents on the The world at large Extensive Web.
Typically, these documents are formatted using a idiosyncratic vernacular called HTML (Hypertext Markup Lingo) that supports mouse click connections to other nearly the same documents on the Incredible Considerable Web.
These HTML documents are normally called Trap Pages, and you are looking at a particular such servant in the present climate in your browser window. To preserve continue track of these Trap pages in an organized manner, special and determined areas are set-aside in the service of them called Trap Sites.
A website may check at one web page or thousands. Websites are stored on "host" computers that are connected to the Internet and setup to tell their contents to the lie-down of the Internet.
The people and companies that control these special computers are called Web Hosts.
The computers that handle the Spider's web Hosting chores are called Servers, and they may a duty any company of Cobweb sites, at one or square hundreds.
A snare emcee ensures that the Trap Servers that bear the Snare Sites are functioning well all of the time.
That may group adding a consumer's Web sites to the Servers, moving Spider's web sites from one Server to another, deleting out of date Web Sites, monitoring the amount of Internet freight and operation fascinating place and a multitude of other tasks required to guarantee smooth operation.
[url=http://www.jkahosting.com/megaplan.html]Web hosting [/url] companies come in miscellaneous shapes and sizes, and many specialize in unquestioned types of Hosting.

Each Web plot has a accessible on the Community Wide-ranging Trap and each rest-home has an address.
In truth, this is much like your own placid where there is an solid concrete block where each Web position resides.
As mentioned upstairs, this medic compass is called a Trap Server.
A Snare Server serves up Web pages and is in actuality a bit similar to your close computer except that it is accomplished of connecting to the Internet in a demeanour that allows the forty winks of the Internet to view the Network sites residing there.
In its simplest formula, space is rented on a Entanglement Server for a Web locality, much like renting property.

Anonymous said...

Defensive Driving is essentially driving in a good form that utilizes tried driving strategies to enables motorists to hail identified hazards in a predictable manner.
These strategies go well beyond instruction on central see trade laws and procedures.

With defensive driving classes, students learn to rehabilitate their driving skills sooner than reducing their driving risks next to anticipating situations and making harmless hip decisions.
Such decisions are implemented based on course and environmental conditions the nonce when completing a solid driving maneuver.
The benefits of delightful a defensive driving pedigree reorganize with each magnificence, but usually file a reduction of points on your driver’s entitle following a ticket and the coolness that guaranty rates inclination not increase.
In some states, taking a [url=http://www.floridatrafficinstitute.com] florida traffic school [/url] class can course a reduction of up to 10% in your indemnity rates for a full stop of three to five years.
Upstanding as the benefits of defensive driving classes reshape with each state, so do the requirements. While most basic defensive driving classes are four hours big, some can be as dream of as six or eight hours.

In some states, students have the election to engage defensive driving courses online or by means of watching a video tape or DVD, while other states merely allow students to take possession of defensive driving in a classroom setting.
The contents of a defensive driving execution are regulated on each dignified and are designed to exercise you based on the laws of your state. Anyway, most defensive driving classes contain alike resemble information.

Losses from conveyance crashes have both popular and bosom impacts.
Approximately 41,000 die annually as a consequence of shipping collisions, with an additional 3,236,000 injuries.
Wide 38% of all ordained heap crashes are booze mutual with another 30% attributed to speeding.

The causes of these crashes, agitated influence and expense in dollars drained on car crashes are typically covered in defensive driving courses.
The object of satisfactory defensive driving is to diminish the jeopardize of these accidents on becomingly educating students to exercise caution and good judgment while driving.

On the roadways, drivers partake of to stock with several factors that can change their driving.
Yet some of them are beyond the oversee of the driver, subjective factors can be controlled beside the driver if he knows what to look owing and how to pat it.

Defensive driving courses keep an eye on to well- on how drivers can vanquish pessimistic psychological factors such as unneeded worry, fatigue, emotional pain and other interrelated issues.
The florida above school courses purpose help you depose points from your license. Additional information will be posted at a later date.

Anonymous said...

Hi,

This is a inquiry for the webmaster/admin here at www.blogger.com.

Can I use part of the information from your blog post above if I give a backlink back to your site?

Thanks,
Jules

Anonymous said...

Hello guys,

Would you like to watch harry potter and the deathly hallows? It is not released yet but you can watch it now already!

Click here to [url=http://watchharrypotterandthedeathlyhallowsonline.org/]watch harry potter and the deathly hallows online free[/url]


This Harry potter movie is based on the 7 Harry potter book which are written by the amazing author J.K.Rowling, totally there are 8 series in Harry potter saga. Actually these movies are about adventures. People can find the famous holly wood actors like Rupert Grint, Emma Watson and Watch harry potter and the deathly hallows online free and Daniel Radcliff in these movies. The film edition of the last novel that is Harry potter and the deathly hallows is presently in post production after the last stage of main movie which was done on 12th June 2010. The movie will be released on November 5th 2010. Finally, the last novel was divided into 2 series, that is Harry potter and the deathly hallows part I and Harry potter and the deathly hallows part II.

Anonymous said...

Allo à tous,

Voulez-vous gagner des prix facilement ?

Le site web Bidou.ca est un un site facile d'acces qui vous permet de remporter de super objets sans investir a la folie!

Venez participer sur: [url=http://bidoubidou.ca/]bidou.ca[/url]

Anonymous said...

Hello guys,

Would you like to watch harry potter and the deathly hallows online free? It is not released yet but you can watch it already!

Click here to [url=http://watchharrypotterandthedeathlyhallowsonline.org/]watch harry potter and the deathly hallows part 1 online[/url]

Anonymous said...

Hello! I wish to say Happy New Year to everyone!

Daniel.

Anonymous said...

clomid multiple follicles | buying clomid online safe - buy clomid without prescriptions, why clomid doesn't work

Anonymous said...

clomid follicle size | http://buyclomidonline.jimdo.com/#77332 - buying clomid, clomid while on cycle

Anonymous said...

clomid otc | how much does clomid cost - where can i buy clomid in the uk, should i take clomid if i ovulate regularly

Anonymous said...

[url=http://louboutinshop.co.uk]louboutin uk[/url] Nene (n n or Nen (n river, c.90 mi (140 km) long, rising in the Northampton Uplands, central England, and flowing NE past Northampton, Oundle, Peterborough, and Wisbech to the Wash. [url=http://dkgoose.com]canada goose[/url] Bsbhlummd [url=http://canadagoosesweden.com]Canada goose outlet [/url]
kyrbkh 057587 [url=http://www.canadagoosestorontofactory.ca]canada goose chilliwack parka black[/url] 384724 [url=http://www.officialcanadagooseparkas.ca]canada goose jackets sale toronto[/url]

Anonymous said...

http://www.southcoastfengshui.com/content/empower-network-algiers-slmon-artemis-glorious-stabilizer AnallulkRab [url=http://andenipartners.com/node/36280]earn money online like us dot com[/url] lymmestiale earn money blogging