Advertisement
Fhernd

AccesoBaseDatosConSemaphoreSlim.cs

Apr 9th, 2015
14,480
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.82 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace Recetas.Multithreading.R0203
  5. {
  6.     public sealed class AccesoBaseDatosConSemaphoreSlim
  7.     {
  8.         // Creación de instancia de `SemaphoreSlim` para controlar el
  9.         // límite de threads = 4:
  10.         public static SemaphoreSlim _ss = new SemaphoreSlim(4);
  11.        
  12.         public static void Main()
  13.         {
  14.             Console.Title = "=== Demostración Uso SemaphoreSlim ===";
  15.             Console.WriteLine();
  16.            
  17.             // Creación de 6 threads:
  18.             for (int i = 1; i <= 6; ++i)
  19.             {
  20.                 string nombreThread = String.Format("T{0}", i.ToString());
  21.                
  22.                 int tiempoEspera = 2 + 2 * i;
  23.                
  24.                 Thread nuevoThread = new Thread( () => AccederBaseDatos(nombreThread, tiempoEspera));
  25.                
  26.                 // Inicio de ejecución de thread:
  27.                 nuevoThread.Start();
  28.             }
  29.            
  30.             Console.WriteLine();
  31.         }
  32.        
  33.         // Método que simula el control del acceso concurrente de threads
  34.         // a una base de datos:
  35.         public static void AccederBaseDatos(string nombreThread, int segundos)
  36.         {
  37.             Console.WriteLine ("Thread `{0}` debe espear para acceder a la base de datos.", nombreThread);
  38.             _ss.Wait();
  39.            
  40.             Console.WriteLine ("Thread `{0}` tiene ahora acceso a la base de datos.", nombreThread);
  41.            
  42.             // Simula operaciones transaccionales o de consulta sobre la base de datos:
  43.             Thread.Sleep(TimeSpan.FromSeconds(segundos));
  44.            
  45.             Console.WriteLine("Thread `{0}` ha finalizado su ejecución", nombreThread);
  46.            
  47.             // Continua la ejecución:
  48.             _ss.Release();
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement