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:

try
{
    System.Threading.Monitor.Enter(obj);
 
    // do some work here
}
finally
{
    System.Threading.Monitor.Exit(obj);
}

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

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>monitor</Title>
      <Shortcut>monitor</Shortcut>
      <Description>Code snippet to use Monitor class for thread-safety</Description>
      <Author>Ashvin Gunga</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>expression</ID>
          <ToolTip>Expression to evaluate</ToolTip>
          <Default>AnObject</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp">
        <![CDATA[
          try
          {
          System.Threading.Monitor.Enter($expression$);
          //TODO: Enter your code here
          $selected$ $end$
          }
          finally
          {
          System.Threading.Monitor.Exit($expression$);
          }]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

>>> 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:

try
{
    System.Threading.Monitor.Enter(AnObject);
 
    //TODO: Enter your code here
}
finally
{
    System.Threading.Monitor.Exit(AnObject);
}

Downloads
Visual Studio 2005 Code Snippets can be downloaded here.

No comments: