{"id":849,"date":"2023-03-10T15:31:48","date_gmt":"2023-03-10T08:31:48","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=849"},"modified":"2023-03-22T10:40:42","modified_gmt":"2023-03-22T03:40:42","slug":"csharp-lock","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-concurrency\/csharp-lock\/","title":{"rendered":"C# Lock"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to use the C# <code>lock<\/code> statement to prevent race conditions and ensure thread safety when multiple threads access shared resources.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Race conditions<\/h2>\n\n\n\n<p>Let&#8217;s start with a simple program:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">int<\/span> counter = <span class=\"hljs-number\">0<\/span>;\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Increase<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n{\n    <span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-keyword\">int<\/span> i = <span class=\"hljs-number\">0<\/span>; i &lt; <span class=\"hljs-number\">1000000<\/span>; i++)\n    {\n        counter++;\n    }\n    Console.WriteLine(<span class=\"hljs-string\">\"The counter is \"<\/span> + counter);\n}\n\nTask.Run(() =&gt; Increase());\nTask.Run(() =&gt; Increase());\n\nConsole.ReadLine();<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, define a variable <code>counter<\/code> and initialize it to zero.<\/p>\n\n\n\n<p>Second, define the <code>Increase()<\/code> method that adds one to the <code>counter<\/code> variable 1 million times and displays the final value of the counter to the console.<\/p>\n\n\n\n<p>Third, create two tasks that run in separate <a href=\"https:\/\/csharptutorial.net\/csharp-concurrency\/csharp-thread\/\">threads<\/a>. Each task executes the <code>Increase()<\/code> method to increase the <code>counter<\/code> variable.<\/p>\n\n\n\n<p>Because both tasks modify the <code>counter<\/code> variable concurrently, it has a risk of race conditions and synchronization problems.<\/p>\n\n\n\n<p>When the program increases the variable <code>counter<\/code>, it carries three steps:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Read the value of the <code>counter<\/code> variable.<\/li>\n\n\n\n<li>Increase it by one.<\/li>\n\n\n\n<li>Write the new value back to the <code>counter<\/code> variable.<\/li>\n<\/ul>\n\n\n\n<p>In other words, the increase of the <code>counter<\/code> variable is not an atomic operation.<\/p>\n\n\n\n<p>Therefore, one task may read the value of the <code>counter<\/code> before the other task has completed updating it, resulting in either an incorrect value or a lost update.<\/p>\n\n\n\n<p>Here&#8217;s the output of the program:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\">The counter <span class=\"hljs-keyword\">is<\/span> <span class=\"hljs-number\">1113815<\/span>\nThe counter <span class=\"hljs-keyword\">is<\/span> <span class=\"hljs-number\">1515277<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Note that you may see different <code>counter<\/code> values when you run the program several times because of the race conditions between two tasks (or threads).<\/p>\n\n\n\n<p>That&#8217;s why the <code>lock<\/code> statement comes to the rescue.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the C# lock statement <\/h2>\n\n\n\n<p>The <code>lock<\/code> statement prevents race conditions and ensures thread safety when multiple threads access the same shared variable.<\/p>\n\n\n\n<p>To use the <code>lock<\/code> statement you create a new object that serves as a lock, which is also known as the mutex. The mutex stands for mutual exclusion.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">lock<\/span>(lockObject)\n{\n   <span class=\"hljs-comment\">\/\/ access the shared resources<\/span>\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>When a thread enters a <code>lock<\/code> block, it will try to acquire the lock on the specified <code>lockObject<\/code>. <\/p>\n\n\n\n<p>If the lock is already acquired by another thread, the current thread is blocked until the lock is released. <\/p>\n\n\n\n<p>Once the lock is released, the current thread can acquire it and execute the code in the <code>lock<\/code> block which often reads or writes the shared resources.<\/p>\n\n\n\n<p>The following program demonstrates how to use a <code>lock<\/code> statement to prevent a race condition between two threads:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">int<\/span> counter = <span class=\"hljs-number\">0<\/span>;\n\n<span class=\"hljs-keyword\">object<\/span> lockCounter = <span class=\"hljs-keyword\">new<\/span>();\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Increase<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n{\n    <span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-keyword\">int<\/span> i = <span class=\"hljs-number\">0<\/span>; i &lt; <span class=\"hljs-number\">1000000<\/span>; i++)\n    {\n        <span class=\"hljs-keyword\">lock<\/span> (lockCounter) \n        { \n            counter++; \n        }\n\n    }\n    Console.WriteLine(<span class=\"hljs-string\">\"The counter is \"<\/span> + counter);\n}\n\nTask.Run(() =&gt; Increase());\nTask.Run(() =&gt; Increase());\n\nConsole.ReadLine();<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>This program is similar to the previous program but uses a lock statement to synchronize access to the <code>counter<\/code> variable. <\/p>\n\n\n\n<p>The <code>lock<\/code> statement ensures that both tasks access the <code>counter<\/code> variable in a mutually exclusive way.<\/p>\n\n\n\n<p>This means that the final value of the counter is predictable and always equal to the sum of increments carried by both tasks, which is <code>2,000,000<\/code>.<\/p>\n\n\n\n<p>Here&#8217;s the output of the program:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\">The counter <span class=\"hljs-keyword\">is<\/span> <span class=\"hljs-number\">1992352<\/span>\nThe counter <span class=\"hljs-keyword\">is<\/span> <span class=\"hljs-number\">2000000<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Note that the final value of the counter is always <code>2,000,000<\/code>. However, the immediate value (<code>1,992,352<\/code>) may vary because the program is running concurrently, with two threads racing to increment the counter variable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">C# lock best practices<\/h2>\n\n\n\n<p>The following are some best practices when using the C# <code>lock<\/code> statement:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Keep the <code>lock<\/code> block as small as possible to minimize the time that other threads have to wait for the lock. If a <code>lock<\/code> block takes a long time to execute, it may cause contention among threads and reduces the application&#8217;s performance.<\/li>\n\n\n\n<li>Avoid nested locks because they may cause a <a href=\"https:\/\/csharptutorial.net\/csharp-concurrency\/csharp-deadlock\/\">deadlock<\/a>. Deadlocks occur when multiple threads try to acquire locks in a different order.<\/li>\n\n\n\n<li>Use <code><a href=\"http:\/\/try...finally\">try...finally<\/a><\/code> block to release the lock properly when an exception occurs in the <code>lock<\/code> block. Also, it ensures other threads are not blocked indefinitely.<\/li>\n\n\n\n<li>Consider using alternative synchronization mechanisms like <code><a href=\"https:\/\/csharptutorial.net\/csharp-concurrency\/csharp-semaphoreslim\/\">SemaphoreSlim<\/a><\/code> and <code><a href=\"https:\/\/csharptutorial.net\/csharp-concurrency\/csharp-readerwriterlockslim\/\">ReaderWriterLockSlim<\/a><\/code> because they can provide better performance and more fine-grained control over concurrency.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the C# <code>lock<\/code> statement to prevent race conditions and synchronization issues when multiple threads access the same shared resources.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"849\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-concurrency\/csharp-lock\/\"\n\t\t\t\tdata-post-title=\"C# Lock\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"849\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-concurrency\/csharp-lock\/\"\n\t\t\t\tdata-post-title=\"C# Lock\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn how to use the C# lock statement to prevent race conditions and ensure thread safety when multiple threads access shared resources.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":760,"menu_order":10,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-849","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/849","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/comments?post=849"}],"version-history":[{"count":5,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/849\/revisions"}],"predecessor-version":[{"id":1174,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/849\/revisions\/1174"}],"up":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/760"}],"wp:attachment":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/media?parent=849"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}