LA.NET [EN]

May 19

[If you’ve just seem a one post sentence, then you’re probably seeing the first Luna’s post :,,) . She has just managed to publish a one line post while I was checking what was on the TV:)]

In the previous post, we’ve taken a quick glance at how we can use the ManualResetEvent. At the time, I did promise another example which might better illustrate its use. So, let’s suppose that we have a class that needs to perform a lengthy operation to initialize a field. Using a ManualResetEvent might be just what the doctor would order (if he could prescribe something for our multithreaded problems 🙂 ). Let’s start by looking at the class code:

class SlowInitializer {
    private String _someInfoThatIsExpensive;
    private ManualResetEvent _evt = new ManualResetEvent(false); //non signaled
    public String SomeInfoThatIsExpensive {
        get {
            _evt.WaitOne();
            _someInfoThatIsExpensive = DateTime.Now.ToString();
            return _someInfoThatIsExpensive;
        }
    }
    public SlowInitializer() {
        new Thread(() => {
            Console.WriteLine("Starting expensive operation at " + DateTime.Now.ToString());
            Thread.Sleep(2000);
            Console.WriteLine("Ended expensive operation");
            _evt.Set();
        }).Start();
    }
}

As you can see, we have a simple class which needs to perform a lot of work (not sure about you, but sleeping is a lot of work sometimes) to initialize the _someInfoThatIsExpensive field. In this case, we’re using an event to ensure that a consumer will only have access to the field *after* it has been properly initialized. Initialization is performed in the constructor and it’s delegated to another thread (ensuring that the thread where the instance is created will only block if it accesses the SomeInfoThatIsExpensive property before initialization is completed). Suppose you have the following code:

var slow = new SlowInitializer();           
new Thread(
    () => Console.WriteLine(DateTime.Now.ToString() + "- " + slow.SomeInfoThatIsExpensive))
    .Start();
new Thread(
    () => Console.WriteLine(DateTime.Now.ToString() + "- " + slow.SomeInfoThatIsExpensive))
    .Start();
Console.WriteLine(DateTime.Now.ToString() + "- " + slow.SomeInfoThatIsExpensive);
Thread.Sleep(1000);
new Thread(
    () => Console.WriteLine(DateTime.Now.ToString() + "- " + slow.SomeInfoThatIsExpensive))
    .Start();

If you try to run the previous snippet, you should get blocked on the Console.WriteLine that precedes the Thread.Sleep (btw, that Thread.Sleep is only there to show you that the last thread has direct access to the property – ie, it won’t get blocked because the event has already transitioned into the signaled state). The following figure shows the results I got on my machine:

manualreset

Notice the time of execution for the several Console.WriteLine instructions…As you can see, this is a good scenario for the ManualResetEvent type. And that’s all for today. Keep tuned for more on multithreading! (as you can see, I’m still learning, but I’m already hooked on this fascinating topic! 🙂 )

8 comments so far

  1. Rrctfkcq
    6:47 pm - 6-24-2009

    89cF9S comment4 ,

  2. gaimbulkilm
    5:21 am - 10-24-2009

    http://www.legalsounds.com/legalsounds/upload/LeftColumnBanner/English.lproj/27.gif http://www.legalsounds.com/legalsounds/upload/LeftColumnBanner/English.lproj/2.png

    Buy Music offers the largest selection of music online. Download mp3 music for as little as 14 cents per song. Why the heck would anybody pay $1 for a $0.14/song? Seriously, Download Mp3s is so cheap these days!

    It would seem that the best online mp3 music site is Soundsbox.com. The site offers 30 second samples of the music, instant mp3 downloads and more. Download Mp3s

    Download Music is the best for playing on an ipod cause mp3 music doesn”t contain any drm (digital rights management). The fact is DRM actually lowers the quality of sound.

    Backgammon Gambling is the online game of the century. BackGammon tournaments and players providing a superior online experience. Gammon Empire provides the largest online community of gammon players.

    Enjoying a awesom internet time playing with Backgammon Software. Playing the game always offers a very relaxing, yet intense feeling.

    Backgammon Tournaments can be found only on sites like GammonEmpire.de.

    If your serious about enjoying life, making money, meeting people online, etc., then you really want to spend some time on Backgammon Play65

    SEO Tools – The only way to promote your website online is to penetrate online established communities. Forums, blogs, guestbooks, and other major community type sites are the perfect platform. Facebook, MySpace and Youtube are also great sites to promote on.

    Online Promotion – Promoting your website online via search engines, online communities, forums, blogs and penetrating online established communities to market your online activity.

    VerifiedFile.com offers the top Search Engine Optimization – Promote your site on Google, MSN & Yahoo

    http://www.seo.com/wp-content/themes/seo/images/home_icon3.gif http://www.nabiscoworld.com/images/header/logo.gif http://www.legalsounds.com/legalsounds/upload/LeftColumnBanner/English.lproj/27.gif http://www.legalsounds.com/legalsounds/upload/LeftColumnBanner/English.lproj/2.pnghttp://www.seo-usa.org/~apicerno//Templates/shared/home//images/seologo.png http://www.nabiscoworld.com/images/header/logo.gif

  3. bruttReardKar
    2:40 am - 10-25-2009

    I”ve been searching all over the internet for a site that will give honest information about acai berry instead of all these scam sites
    Well I finally came across one that was honest and truthful about the benefits of using acai berry as a supplement to your health
    If your looking for a honest supplment that will help you lose weight the best site is Acai Berry Diet
    it”s prolly best to use acai berry as a supplment and to make sure you still exercise and diet carefully. Acai Berry Tropic
    http://acaiberrydiet.org

  4. Vawsbyday
    4:11 pm - 12-2-2009
  5. Shiedgenign
    7:08 am - 12-5-2009

    http://verifiedfile.com/images/software.jpg

    Do you think the above software is just too expensive?
    Then check out CdrbSoftware.com and get your software at just a fraction of the cost!

    Just fill up your own customized DVD full of all the software you want at a very low flat rate cost!
    Then select to have the DVD shipped to your address or just download your order, or both! Over a 1000 software titles available!

    Our Customer Commitment: http://verifiedfile.com/images/smile.gif
    We respond to all emails within a few hours.
    Full After Sales support.
    If you have any problem installing the software, just email us for support.
    Any problem get”s resolved or a refundhttp://www.tunespro.com/images/1pixel.gif

  6. choockisk
    1:19 am - 1-31-2010

    Bonjour I”d love to congratulate you for such a great quality site!
    Just thought this would be a nice way to make my first post!
    To pile fortune it is usually a good conclusion to start a savings or investing plan as soon in life as feasible. But don”t despair if you have not started saving your capital until later on in life. As a result of hard work, that is consulting the best investment vehicles for your money you can slowly but surely increase your riches so that it measures to a sizable amount by the time you want to retire. Review all of the achievable asset classes from stocks to real estate as investments for your money. A knowledgeable and diversified portfolio of investments in various asset classes will help your money enlarge throughout the years.

    -Kelly Siemers
    currency exchange rates

  7. mathhoang
    4:43 am - 2-2-2010

    it”s good => but shoul use a simple code to illustrate for newbies