From the course: Ten Tips for the C# Developer

Avoid race condition with TryGetValue method - C# Tutorial

From the course: Ten Tips for the C# Developer

Start my 1-month free trial

Avoid race condition with TryGetValue method

It's a good idea, to try to write the right safe code, wherever possible, in your C sharp application. There are multiple ways, of doing that in C sharp, and in.net. I want to look at one method, on the dictionary class. That will help you. It's called the try-get-value. We'll start by looking at the code here at the beginning. At the top of my show example method, of declaring to integer variables. Then I'm instantiating a dictionary, that has a string as the key, and an int as the value. I then add three items to the dictionary, 10, 20, and 30, and I have matching string keys. Here's the code that you don't want to write. There's a possible race condition here. on line 23, I go to the dictionary, and verify, that it contains the key called 30. If it does contain that key, then on line 27, I get the value, with that key, and store it in this variable, and then on line 29, I do a calculation. Now the problem here, with this code, is that, between line 23 running, and line 27 running, another thread could come along, and remove the item in the dictionary, And then I'm going to have trouble on line 27. The better approach to this, is to use ,this code here, and I notice it's still an if statement, this time my if statement says, try to get the value, and it checks for this key, and then assigns the value to this out parameter if it exists in the dictionary. the rest of the code is the same. The difference is I've cached , the copy of the value here in this result variable. So even if ,the dictionary item gets removed, by the time we get to line 36, I've got the cached copy here in this result, variable. So that's the tip, use try-get-value, to write the right safecode and your if statements.

Contents