Monday, October 27, 2008

Code Snippets: Monitor class for thread-safety

Code Snippets is an interesting in-built feature of Visual Studio 2005. Code snippets are normally used in the Code Editor by first typing a shortcut (short name or alias), and then pressing TAB key. The code snippet shortcut/alias will then expand into a programming construct. This can make writing program code quicker, easier and more reliable.

To use the code snippets, use any of the follwing ways:

1. Right click in Code Editor and select the Insert Code Snippet menu command,
2. Activate the code snippet list by typing CTRL + K followed by X.

The Code Snippets Manager, found under the Tools menu, allows us to manage code snippets (add/remove) that will be available to insert into the code. It can also be accessted by CTRL K, followed by B.

The code snippets are stored as XML in .snippet files, and any user-defined snippet can be easily imported through the Code Snippets Manager and used during coding.

As a example, I will write a code snippet in order to use the Monitor.Enter and Monitor.Exit methods for thread-safe code (as we already have the 'lock' code snippet in VS2005) as shown below:

    // do some work here

>>> Create the code snippet and store it as monitor.xml

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="">
  <CodeSnippet Format="1.0.0">
      <Description>Code snippet to use Monitor class for thread-safety</Description>
      <Author>Ashvin Gunga</Author>
          <ToolTip>Expression to evaluate</ToolTip>
      <Code Language="csharp">
          //TODO: Enter your code here
          $selected$ $end$

>>> Use the Code Snippets Manager and import the monitor.snippet file under My Code Snippets

>>> Now, in the code, type monitor and press TAB. The monitor shortcut is expanded to:

    //TODO: Enter your code here

Visual Studio 2005 Code Snippets can be downloaded here.

No comments: