Mutex Snippet for Windows Phone 7
I created a little snippet for my app called “Surround with Mutex”. Basically it protects any call to the isolated storage with a Mutex.
A Mutex is: “A synchronization primitive that can also be used for interprocess synchronization.”
http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx
I had to use this due to my foreground and background agent possibly making calls at the same time to my files within isolated storage. If you do not protect your calls with a Mutex it is possible you could corrupt the data files within isolated storage. I had help with the Mutex with this bit of code example: http://www.albahari.com/threading/part2.aspx#_Mutex
I then took it for my needs and created a snippet for Visual Studio 2010. I named my snippet file Mutex.snippet.
It is essentially just an XML document with the code below. Instead of having file named Mutex.xml it needs to be renamed to Mutex.snippet.
<?xml version=”1.0” encoding=”utf-8” ?>
<CodeSnippet Format=”1.0.0” xmlns=”http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet”>
<Header>
<Title>Surround with Mutex</Title>
<Author>your name here</Author>
<Shortcut>smutex</Shortcut>
<Description>Surround with Mutex</Description>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Code Language=”CSharp”>
<![CDATA[
// Naming a Mutex makes it available computer-wide. Use a name that’s
// unique to your company and application (e.g., include your URL).
using (var _mutex = new Mutex(false, “myappmutex-www.yourwebaddress.com”))
{
// Wait a few seconds if contended, in case another instance
// of the program is still in the process of shutting down.
if (!_mutex.WaitOne(TimeSpan.FromSeconds(3)))
{
return;
}
$selected$ $end$
}
]]>
</Code>
</Snippet>
</CodeSnippet>
Once this file is created in your project you need to add it to your snippet library. You can do this by going to Tools->Code Snippet Manager… then clicking Import…


Then select the snippet you created “Mutex.snippet”. Once you have done this, your snippet is immediately available for use. I just select the code I would like to surround with the Mutex and press control+K, control+S then I am able to use the snippet I created.


