Convert to Parallel

Converts the code to run in parallel. Refactoring is available in the following cases:

Case Description
In a for loop Refactoring uses a call to the Parallel.For() method instead of the initial for loop.
In a foreach loop Refactoring uses a call to the Parallel.ForEach() method instead of the initial foreach loop.
In a query Refactoring uses a call to the asParallel() method of an IEnumerable object instead of the reference to this object.

Notes

  • If you use Visual Studio 2008, the Convert to Parallel refactoring requires Parallel Extensions to be installed and the System.Threading namespace to be added to the project references list.

Availability

Available from the context menus or via shortcuts:

  • when the edit cursor or caret is on the for keyword of a loop.
  • when the edit cursor or caret is on the foreach keyword of a loop.
  • when the edit cursor or caret is on a reference to an IEnumerable object within a query.

A for loop example

for (int i = 0; i < 1000; i += 2)
{
   MyMethod(i.ToString());
}
Private Sub TestMethod1()
    For i = 0 To 1000 Step 2
        MyMethod(i.ToString())
    Next i
End Sub

Result:

Parallel.For(0, 1000, 2, i =>
{
    MyMethod(i.ToString());
});
Sub DelegateMethod(ByVal MyItem As String)
    MyMethod(MyItem)
End Sub
Private Sub TestMethod1()Parallel.For(0, 1000, 2, AddressOf DelegateMethod)
End Sub

A foreach loop example

private void TestMethod2(List<string> MyList)
{foreach (string MyItem in MyList)
    {
        MyMethod(MyItem);
    }
}
Private Sub TestMethod2(ByVal MyList As List(Of String))For Each MyItem As String In MyList
        MyMethod(MyItem)
    Next MyItem
End Sub

Result:

private void TestMethod2(List<string> MyList)
{Parallel.ForEach(MyList, MyItem =&gt;
    {
        MyMethod(MyItem);
    });
}
Sub DelegateMethod(ByVal MyItem As String)
    MyMethod(MyItem)
End Sub
Private Sub TestMethod2(ByVal MyList As List(Of String))Parallel.ForEach(MyList, AddressOf DelegateMethod)
End Sub

A query example

private string TestMethod3(List<string> MyList)
{
    return (from str in MyList select str.ToLower()).First&lt;string&gt;();
}
Private Function TestMethod3(ByVal MyList As List(Of String)) As String
    Return (From str In MyList Select str.ToLower()).First()
End Function

Result:

private string TestMethod3(List<string> MyList)
{
    return (from str in MyList.AsParallel() select str.ToLower()).First&lt;string&gt;();
}
Private Function TestMethod3(ByVal MyList As List(Of String)) As String
    Return (From str In MyList.AsParallel() Select str.ToLower()).First()
End Function

Screenshot

rsConvertToParallelCSharp

See Also