Code Snippets for Parallel.For and Parallel.ForEach

Stephen Toub - MSFT

Introduced in Visual Studio 2005, Code Snippets allow you to quickly insert reusable blocks of code into your project.  For example, if you want to quickly write a for loop in C#, you can simply type “for” into your code file, and IntelliSense shows you the “for” code snippet:

image

Now you press the tab key twice, and Visual Studio automatically expands this for you into a for loop, allowing you to quickly replace things like the iteration variable’s name:

image

One of the coolest things about Code Snippets, however, is that you can write your own.  Imagine being able to type “parall” and have a Code Snippet for Parallel.For pop up:

image

When you expand this, you’d get a Parallel.For loop:

image

“Magic,” you say?  Not quite.  All you have to do is write a custom snippet that looks as follows:

<?xml version=”1.0″ encoding=”utf-8″ ?>
<CodeSnippets  xmlns=”http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet”>
    <CodeSnippet Format=”1.0.0″>
        <Header>
            <Title>parallelfor</Title>
            <Shortcut>parallelfor</Shortcut>
            <Description>Code snippet for ‘Parallel.For’ loop</Description>
            <Author>Microsoft Corporation</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
                <SnippetType>SurroundsWith</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>index</ID>
                    <Default>i</Default>
                    <ToolTip>Index</ToolTip>
                </Literal>
        <Literal>
          <ID>from</ID>
          <Default>from</Default>
          <ToolTip>From</ToolTip>
        </Literal>
                <Literal>
                    <ID>to</ID>
                    <Default>to</Default>
                    <ToolTip>To</ToolTip>
                </Literal>
            </Declarations>
            <Code Language=”csharp”><![CDATA[Parallel.For($from$, $to$, $index$ =>
            {
            $selected$ $end$
            });]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

Save that to a file parallelfor.snippet in a directory of your choosing.  In Visual Studio, go to Tools | Code Snippet Manager…, add the directory into which you stored the snippet, and you’ll be off and running.

The parallelfor snippet file as well as another example for parallelforeach are attached to this blog post.  Are there any other useful snippets you’d be interested in having related to parallel programming in general or specifically to Parallel Extensions?

Enjoy!

ParallelSnippets.zip

0 comments

Discussion is closed.

Feedback usabilla icon