Skip to content

Commit b8092c0

Browse files
authored
Update example.cs (#4864)
Added `try{} finally{}` blocks to ensure releasing of the lock
1 parent ad5c5a5 commit b8092c0

File tree

1 file changed

+13
-7
lines changed
  • samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.semaphoreslim/cs

1 file changed

+13
-7
lines changed

samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.semaphoreslim/cs/example.cs

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,17 +25,23 @@ public static void Main()
2525
// Each task begins by requesting the semaphore.
2626
Console.WriteLine("Task {0} begins and waits for the semaphore.",
2727
Task.CurrentId);
28+
29+
int semaphoreCount;
2830
semaphore.Wait();
31+
try
32+
{
33+
Interlocked.Add(ref padding, 100);
2934

30-
Interlocked.Add(ref padding, 100);
31-
32-
Console.WriteLine("Task {0} enters the semaphore.", Task.CurrentId);
33-
34-
// The task just sleeps for 1+ seconds.
35-
Thread.Sleep(1000 + padding);
35+
Console.WriteLine("Task {0} enters the semaphore.", Task.CurrentId);
3636

37+
// The task just sleeps for 1+ seconds.
38+
Thread.Sleep(1000 + padding);
39+
}
40+
finally {
41+
semaphoreCount = semaphore.Release();
42+
}
3743
Console.WriteLine("Task {0} releases the semaphore; previous count: {1}.",
38-
Task.CurrentId, semaphore.Release());
44+
Task.CurrentId, semaphoreCount);
3945
});
4046
}
4147

0 commit comments

Comments
 (0)