From the course: Advanced C#: Thread-Safe Data with Concurrent Collections

Unlock this course with a free trial

Join today to access over 22,400 courses taught by industry experts.

Use a lock statement and mutex to make thread-safe

Use a lock statement and mutex to make thread-safe - C# Tutorial

From the course: Advanced C#: Thread-Safe Data with Concurrent Collections

Use a lock statement and mutex to make thread-safe

- [Instructor] I'll show you two techniques for locking a section of code. I'll start by showing you the C Sharp lock statement and then we'll also look at how to use the mutex class to lock a segment of code. I'll start by writing the code here and make robot and I need to figure out which of these lines of code should have the lock applied. Now one way you can think about this, is there any place in this method that is modifying shared state? And I can see here on line 55, that is true. I've got this class level variable called underscore ID counter, and I'm incrementing that value. So what could happen is thread one enters here, and sets ID counter to one, and then before we get to line 56, that thread is suspended and another thread enters here and increments this counter to two, and then the first thread resume. So now when it gets to line 56, instead of having the value of one here for setting the ID,…

Contents