2015-11-06 184 views
0

大圖是從1打印一個Thread t到某個值,然後暫停執行,取決於signal (ManualResetEvent)期間執行另一個線程s執行。 s完成後,它sets the signal。因此,T恢復執行。預期上半年直到線程t暫停時signal是在WorkOnKeyReachedreset帶線程事件處理

class A 
{ 
    int key; 
    int temp; 
    public A(int x) 
    { 
     key = x; 
    } 
    public EventHandler eventHandler; 
    private void onKeyReached(object sender, EventArgs e) 
    { 
     eventHandler(this, e); 
    } 
    public int Temp 
    { 
     get { return temp; } 
     set 
     { 
      if (value == temp) return; 
      else if (temp == key) 
       onKeyReached(this, EventArgs.Empty); 
      else 
       temp = value; 
     } 
    } 
} 
class Test 
{ 
    static A a = new A(500); 

    //signal to pause or resume threads 
    static ManualResetEvent signal = new ManualResetEvent(true); 

    static void Main() 
    { 
     a.eventHandler += WorkOnKeyReached; 

     Thread t = new Thread(F); 
     t.Start(); 
    } 
    static void F() 
    { 
     for (int i = 0; i < 1000; i++) 
     { 
      a.Temp = i; 
      //when a.Temp == a.Key, a.OnkeyReached() is fired. 
      signal.WaitOne(); 
      Console.WriteLine(a.Temp); 
     } 
    } 
    static void WorkOnKeyReached(object sender, EventArgs e) 
    { 
     signal.Reset(); 
     Thread s = new Thread(() => 
     { 
      Console.WriteLine("Doing something else..."); 
      Thread.Sleep(3000); 
      Console.WriteLine("Done.."); 
      signal.Set(); 
     }); 
     s.Start(); 
    } 
} 

計劃工作。 然而WorkOnKeyReached完成後,我setsignal預期t繼續。

輸出繼電器:

1 
2 
.. 
500 
Doing something else... 
Done. 
500 
Doing something else... 
Done. 

誰能幫助解釋這一現象?我只是在玩線程和其他東西。

+0

我可以告訴你,現在對A類臨時二傳手不是線程安全 – William

+0

爲什麼'a.Temp = i'不安全?我明白只有1個線程執行該行。 –

回答

0
public int Temp 
{ 
    get { return temp; } 
    set 
    { 
     if (value == temp) return; 
     else if (temp == key) 
      onKeyReached(this, EventArgs.Empty); 
     //else 
      temp = value; 
    } 
} 

基本上取出否則就永遠不會增加近500