2017-02-16 25 views
-1

我有一個屬性,可以從Invoke()(從線程)和其他沒有invoke()在同一類中的方法修改。只是詢問,關於在主線程中調用()

如果他們在同一時間被調用會發生什麼?

這可能嗎?由於可以在某些方法中影響條件。

例如:

public class Test{ 
    public bool testBool { get; set; } 

    public void MethodWIthInvoke(){ 
     this.Invoke(new Action(() => 
     { 
      if (testBool) 
      { 
       testBool = false; 
      } 
     })); 
    } 

    public void Method(){ 
     if (testBool) 
     { 
      testBool = false; 
     } 
    } 
} 
+0

只要從Method接口調用Method(),就會好的。 – itsme86

+0

是的,'Method()'只從UI線程調用,如果它們同時運行會發生什麼? – Cristian18

+0

@ Cristian18他們不能,如果他們都從同一個線程運行。它會做一個或另一個。 – Servy

回答

-1

我不知道爲什麼你需要讓這樣的代碼,無論如何,因爲這兩種方法都將在同一個線程調用那麼這將是罰款。我想提出另一種方法來編寫代碼,如下所示:

public class Test{ 
public bool testBool { get; set; } 

public void Method() 
    { 
     if (this.InvokeRequired) 
     { 
      this.Invoke(new Action(() => 
      { 
       if (testBool) 
       { 
        testBool = false; 
       } 
      })); 
     } 
     else 
     { 
      if (testBool) 
      { 
       testBool = false; 
      } 
     } 
    } 
}