Note that there are some explanatory texts on larger screens.

plurals
  1. POConditional thread locking
    primarykey
    data
    text
    <h1>Scenario</h1> <p>I want to download resources. I don't want a resource to be downloaded more that once. If thread <em>a</em> downloads resource <code>1</code> it should be cached, and thread <em>b</em> should wait and use the cached resource <code>1</code> if it attempts to download resource <code>1</code> at the same time. If thread <em>c</em> wants to download resource <code>2</code>, it should not be influenced by thread <em>a</em> and <em>b</em>.</p> <h1>Attempt</h1> <p>I have tried to implement the scenario below:</p> <pre><code>using System; using System.Collections.Generic; using System.Threading; namespace ConsoleApplication1 { class ConditionalThreadLockingProgram { private static readonly object _lockObject = new object(); private static readonly Dictionary&lt;int, string&gt; Locks = new Dictionary&lt;int, string&gt;(); private static readonly Dictionary&lt;int, string&gt; Resources = new Dictionary&lt;int, string&gt;(); public static string GetLock(int resourceId) { lock (_lockObject) { if (Locks.ContainsKey(resourceId)) { return Locks[resourceId]; } return Locks[resourceId] = string.Format( "Lock #{0}", resourceId ); } } public static void FetchResource(object resourceIdObject) { var resourceId = (int)resourceIdObject; var currentLock = GetLock(resourceId); lock (currentLock) { if (Resources.ContainsKey(resourceId)) { Console.WriteLine( "Thread {0} got cached: {1}", Thread.CurrentThread.Name, Resources[resourceId] ); return; } Thread.Sleep(2000); Console.WriteLine( "Thread {0} downloaded: {1}", Thread.CurrentThread.Name, Resources[resourceId] = string.Format( "Resource #{0}", resourceId ) ); } } static void Main(string[] args) { new Thread(FetchResource) { Name = "a" }.Start(1); new Thread(FetchResource) { Name = "b" }.Start(1); new Thread(FetchResource) { Name = "c" }.Start(2); Console.ReadLine(); } } } </code></pre> <h1>Question</h1> <p>Does it work? Any issues?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload