2017-03-17 25 views
0

我只需要創建一個函數複選框,將返回複選框的當前值。InvokeRequired複選框

我寫道:

private void Checkbox_check() 
     { 
      if (checkBox1.InvokeRequired) 
       return (int)checkBox1.Invoke(new Func<int>(checked)); 
      else 
       return checkBox1.Checked; // bad here i know 

     } 

什麼是壞在這裏,可以有人只是正確地寫入這個功能呢?我需要調用,因爲不能在沒有調用的情況下在另一個線程中使用。我只是搜索一個論壇和網站的幫助,但無法找到解決方案。

+0

我認爲這裏的錯誤是該方法返回void,並且返回實際值。 – Maarten

+0

絕對不要這樣寫代碼,這是最終的線程比賽錯誤。在開始線程之前獲取UI值。並確保用戶在線程運行時不能更改它(使用Enabled屬性),以便在線程中計算的結果始終與UI狀態保持一致。 BackgroundWorker使這一切變得簡單。 –

回答

0

不要使用Func<>,因爲它不返回任何東西。改爲使用Action

private void Checkbox_check() 
{ 
    if (checkBox1.InvokeRequired) 
     checkBox1.Invoke(new Action(Checkbox_check)); 
    else 
    { 
     // do what you like to do on the ui context 
     // checkBox1.Checked; // bad here i know, yep... 
    } 
} 

從另一個線程獲取的選中狀態,你可以這樣做:

private bool Checkbox_check() 
{ 
    // result value. 
    bool result = false; 

    // define a function which assigns the checkbox checked state to the result 
    var checkCheckBox = new Action(() => result = checkBox1.Checked); 

    // check if it should be invoked.  
    if (checkBox1.InvokeRequired) 
     checkBox1.Invoke(checkCheckBox); 
    else 
     checkCheckBox(); 

    // return the result. 
    return result; 
} 

我不會建議這,這可能導致死鎖等。我勸你傳遞檢查threadstart上的值,因此不必執行任何crossthread調用。

+0

我只需要稍後在我的主題中使用此功能。我怎麼寫這個?我需要像這樣使用:If(checkbox1.Checked){}。那麼如何正確寫入Checkbox_Check來做到這一點?我的意思是後來只需要:if(Checkbox_check.Checked。){} – Adamszsz

+0

@Adamszsz你想檢查從其他線程的複選框檢查狀態? –

+0

Exacly YES我只需要調用我認爲 – Adamszsz

-1

你應該寫這樣說:

private void Checkbox_check() 
    { 
     if (checkBox1.Invoke:DRequired) 
      return (int)checkBox1.Invoke(new Func<int>(checked)); 
     else 
      return checkBox1.Checked.(initInvoke); 
    } 
+0

這看起來不合編。 (1)'return checkBox1.Checked。(initInvoke); '該方法不返回'int'(2)'checkBox1.Checked。(initInvoke); '檢查是一個屬性,而不是一個函數。你自己測試一下嗎? –