多线程同步问题解决方法之一---使用lock

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5: using System.Threading;
   6: using System.Threading.Tasks;
   7:  
   8: namespace SynchronizationSamples
   9: {
  10:     public class SharedState
  11:     {
  12:         private int state = 0;
  13:         private object syncRoot = new object();
  14:         public int State 
  15:         { 
  16:             get{return state;}
  17:             set { state = value; }
  18:         }
  19:  
  20:         public int IncrementState()
  21:         {
  22:             lock (syncRoot)
  23:             {
  24:                 return ++state;
  25:             }
  26:             
  27:         }
  28:     }
  29:  
  30:     public class Job
  31:     {
  32:         SharedState sharedState;
  33:         public Job(SharedState sharedState)
  34:         {
  35:             this.sharedState = sharedState;
  36:         }
  37:  
  38:         public void DoTheJob()
  39:         {
  40:             for (int i = 0; i < 50000;i++ )
  41:             {
  42:                 lock (sharedState)
  43:                 {
  44:                     sharedState.State += 1;
  45:                 }
  46:             }
  47:         }
  48:     }
  49:     class Program
  50:     {
  51:         static void Main(string[] args)
  52:         {
  53:             int numTasks = 20;
  54:             var state = new SharedState();
  55:             var tasks = new Task[numTasks];
  56:  
  57:             for (int i = 0; i < numTasks; i++)
  58:             {
  59:                 tasks[i] = new Task(new Job(state).DoTheJob);
  60:                 tasks[i].Start();
  61:             }
  62:  
  63:             for (int i = 0; i < numTasks;i++ )
  64:             {
  65:                 tasks[i].Wait();
  66:             }
  67:             Console.WriteLine("summarized {0}",state.State);
  68:             Console.Read();
  69:         }
  70:     }
  71: }

你可能感兴趣的:(Lock)