Lock to Try/Finally

Converts a lock() (SyncLock in VB) statement into a try/finally statement.

Availability

Available from the context menu or via shortcuts:

  • when the edit cursor, or caret is on a lock statement ("lock" keyword).
Note

This refactoring is available in C# only.

Example

private void TestMethod()
{
    Object objVar = new Object();lock (objVar)
    {
        UseObjVar(objVar);
    }
}
Private Sub TestMethod()
  Dim objVar as Object = new Object()SyncLock objVar
    UseObjVar(objVar);
  End SyncLock
End Sub

Result:

private void TestMethod()
{
    Object objVar = new Object();System.Threading.Monitor.Enter(objVar);
    try
    {
        UseObjVar(objVar);
    }
    finally
    {
        System.Threading.Monitor.Exit(objVar);
    }
}
Private Sub TestMethod()
  Dim objVar as Object = new Object()System.Threading.Monitor.Enter(objVar)
  Try
    UseObjVar(objVar)
  Finally
    System.Threading.Monitor.Exit(objVar)
  End Try
End Sub

Animation

rsLockToTryFinallyCSharp