多線程改變變量的值是不安全的

 //最後的結果 LongCount 和AllCount不相等

線程中改變變量的值需要慎重考慮

decimal LongCount = 0;
decimal AllCount= 0;
//最後的結果 LongCount 和AllCount不相等
public void StartTheed(int ThreadCount)
{
 for (int i = 0; i < ThreadCount; i++)
 {
     Thread PopRec1 = new Thread(new ParameterizedThreadStart(Control));
    PopRec1.IsBackground = true;
    PopRec1.SetApartmentState(ApartmentState.STA);
    PopRec1.Start("A");              
 }
}
public void Control(object Str)
 {
  decimal Count= 0;
  try
     {              
        while (Run)
        {
            LongCount++;
            Count++;
            if(Count>2000)
            {
                break;
            }
        }
        AllCount=AllCount+Count;
     }
     catch (Exception ex)
    {
        throw ex;
    }
}

猜你喜欢

转载自blog.csdn.net/losedguest/article/details/81901198