Thread Safety in .NET–Difference Between using Monitor.Enter and Monitor.Exit and lock

   When we want to develop ThreadSafe solutions .NET two of the options that we can use are Monitor and lock. But what exactly happens when we use one and another? What are the differences between one and the other?

   Basically the difference is that lock really emits code that places a a Monitor inside a try…finally block. So the real difference is that lock really gives us a exception proof Monitor, since it makes sure that it gets free of that locking even if an exception occurs.

   So lets see a sample of that:

     Imagine this as the code that we write using lock.

   1:              object something = new object();
   2:              lock (something)
   3:              {
   4:                  var query = new TargetProcessEntities()
.Bug.Where(bug => bug.BugID > 100);
   6:                  foreach (var bug in query)
   7:                  {
   9:                      Console.WriteLine("{0}", bug.BugID);
  11:                  }
  12:              }

.csharpcode, .csharpcode pre
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
background-color: #f4f4f4;
width: 100%;
margin: 0em;
.csharpcode .lnum { color: #606060; }

     The generated code will be: (using .NET Reflector)
   1:          object CS$2$0000;
   2:          object something = new object();
   3:          bool <>s__LockTaken0 = false;
   4:          try
   5:          {
   6:              Monitor.Enter(CS$2$0000 = something, 
ref <>s__LockTaken0);

7: IQueryable<Bug> query = from bug in

new TargetProcessEntities().Bug

   8:                  where bug.BugID >= 100
   9:                  select bug;
  10:              foreach (Bug bug in query)
  11:              {
  12:                  Console.WriteLine("{0}", 
  13:              }
  14:          }
  15:          finally
  16:          {
  17:              if (<>s__LockTaken0)
  18:              {
  19:                  Monitor.Exit(CS$2$0000);
  20:              }
  21:          }

.csharpcode, .csharpcode pre
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
background-color: #f4f4f4;
width: 100%;
margin: 0em;
.csharpcode .lnum { color: #606060; }

  So as we can see the lock that we placed in the original code at line 2, really gave place to a try…finally block like we can see at lines 4…6 and 14…21.

  Basically when we need to use locks in order to have Thread Safety, than we should use lock instead of Monitor.Enter and Monitor.Exit, since lock really gives us an optimized way to use the Monitor class.

  I’d like to thank Richard Blewett for his great explanation of it.

Microsoft TechDays 2010 Portugal – Entity Framework 4.0 Evolution and Future

   So another session that I did at Microsoft TechDays 2010 Portugal was around Microsoft Entity Framework 4.0 Evolution and features we can expect in the future. And being a 400 Level session I tried to do it as much sample based and interactive as possible, by asking the attendees what were their normal pains when using Entity Framework or any other ORM framework that they were working on, and show a sample of how to do that. Unfortunately there wasn’t as much interaction as I was expecting, but still we could see the most recent evolutions on this technology.

  Here’s a summary of what this session was:

  • Slight Introduction to Entity Framework and how that is part of the Data Platform Group, and what other elements are also at that group, and those are:
    • Visual Studio Integration
    • Quadrant
    • Entity Framework
    • WCF Data Services
    • OData
    • ADO.NET
    • “M” / EDM
    • SQL Server
    • SQL Azure
    • SQL Modeling Services
  • New features
    • Model-First Development
      • We are now able to achieve an approach where we do the EF Model first and after that we generate the database based on that, or only map the Storage Model into it.
    • Automatic Pluralization
      • The model now has the capability of instead of making the EntitySets named something like the name of the entity and adding Set to the name (ex. Person, PersonSet), we now have the option to pluralize that and it will do that automatically for us (ex. Person, People)
    • Foreign Keys in models
      • Previously we didn’t had the foreign keys of the navigation properties on our models, now we do.
    • POCO Support
    • Lazy Loading
      • Now lazy loading is on by default and really works without having to use Include like it was previously
    • T4 Code Generation
      • A complete set of T4 templates we can use and customize to define how we want our code files to be generated
    • Template Customization (same as before)
    • IObjectSet
      • Now we have an interface that is IObjectSet that is the basis of out EntitySet, and what this allows us to do, is create our our POCO classes that are Self-tracking
    • Virtual SaveChanges method
      • In this version we have SaveChanges marked as virtual, and so we can override that and place our own code in there.
    • ObjectStateManager object
      • Manages the state of our objects
    • Self-tracking Entities
      • Capability of doing some entities that are responsible for their own change management, and also aware of those changes
    • SQL Generation Improvements
      • Huge leap in terms of performance, since a lot was done in order to get the best possible sql code generated based on the Linq query. Examples like the usage of Like clause in SQL when we in Linq use the Contains method, instead of the previously used CharIndex.
    • More Linq operator support
      • Contains
      • DefaultIfEmpty
      • Single, SingleOrDefault (in top projection)
      • ExecuteStoreQuery and Translate
    • Linq Extensibility
    • ExecuteStoreQuery
    • ExecuteStoreCommand
    • Stored Procedures Import improvements
      • Capability of having Store Procedures imported to the model as Methods, as well as having also functions as part of the model methods
    • Model defined functions (same as above)
    • WPF designer integration
      • New Designer in VS2010 is done in WPF
    • Code-only development (Only at EF Features CTP3)
      • Possibility of having all the EF model being done in code without using edmx, csdl, ssdl or msl files. All of this will be described in code.
  • Possible Routes using Entity Framework
    • Start with the database
      • Database-first approach
    • Start with the Model
      • Model-first approach
    • Start with .net classes
      • Code-first approach


You can find this presentation here and on SlideShare:

TechDays 2010 Portugal – Entity Framework 4.0 Evolution and Future – 16×9

View more presentations from Nuno.Godinho.

I would enjoy very much to ear your thoughts about this presentation.

Microsoft TechDays 2010 Portugal – Microsoft Silverlight Analytics Framework – 360° look

   It has been a while since I last wrote about my Microsoft TechDays 2010 Portugal sessions, and being really true, it’s been a while since I wrote anything at all, but here I go now of to another start in writing.

  So another session that I did at the Portuguese TechDays 2010 event was about Microsoft Silverlight Analytics Framework, and this was done with my friend Ricardo Castelhano. The purpose of this presentation was to give a 360° view of this new Silverlight Framework and what it could mean for our solutions. And as you know Analytics is a very important part of our applications, and I’m not only talking about analytics of page hits, or that sort of things that normally Marketing people want measured, because we need more than that. Imagine if we could understand how our application is working by using this Analytics capabilities, and by doing that we would be instrumenting our application. This was exactly what we talked about.

  The summary of this session is the following:

  • Design Goals
    • Support All the possible usages of Silverlight Applications, and not only when they are on the browser
    • Support for multiple analytics services to work simultaneously without impacting the Performance
    • Giving Support for Designers to easily use this framework
    • Support A/B Testing
    • Support for event SketchFlow prototypes
    • Support for Silverlight Media Framework
  • Architecture
    • At this level what happens is that we have 3 (three) elements associated with the way this works, and those are:
      • Silverlight Control
        • Object that will be analyzed
      • Data Collector
        • Element that will receive every analysis information and send it to the right Event Log
      • Event Log
        • Element that will receive and store the analysis information
        • Ex. Event Viewer
  • How does this work?
    • All Silverlight Analytics Framework objects are really Silverlight Behaviors that interact with some specific element
  • Extensibility
    • There are 3 (three) ways that this framework is being extended, and those are:
      1. Analysis Services
        • This includes the creation of new behaviors
        • Several Microsoft Partners and other vendors are doing this for us
      2. Control Vendors
      3. Visual Studio Templates
        • Templates that are available for Visual Studio in order to ramp-up the new analytical behaviors.
  • Partners
    • Launch Partners
      • Included in the Framework installer
        • AT internet
        • Comscore
        • GlanceGuide
        • Google Analytics
        • Nedstat
        • Preemptive Solutions
        • Quandcast
      • Supported by Control library
        • Telerik
    • Additional Committed Partners
      • Anvato
      • Conviva
      • Nielsen
      • Skytide
      • Visible Measures
      • Webtrends
      • Unica
      • Infragistics
  • ShowCase
    • RTL Gemist
  • Platforms
    • Silverlight
    • WPF
  • Release Information
    • Beta Release at MIX10
      • Silverlight 3
      • Blend 3
      • VS2008
      • Microsoft Silverlight Media Framework 1.0
      • Smooth Streaming Media Element
    • SDK RTW
      • Silverlight 4
      • Blend 4
      • VS2010
      • Microsoft Silverlight Media Framework 1.0
      • Smooth Streaming Media Element
  • Availability

You can find this presentation here and on SlideShare:

I would enjoy very much to hear your thoughts about this presentation.