2013-07-12 15 views
0

問題1我想知道是否可以在內部操作的回調中停止循環?
問題2.我可以在回撥中停止SomeMethod()嗎?回調中的停止方法和循環

E.g.我有這樣一個代碼:

foreach(...) 
{ 
    myObject.SomeMethod(s => 
     { 
     // something break-like here to stop foreach/method? 
     }); 
} 

[編輯]

這是我使用的代碼的例子 - 它不工作,因爲我想要的。

bool test = false; 
foreach (var drive in drives) 
{ 
    foundFolders.AddRange(
     DirectoryWrapper.GetDirectories(drive, regex, true, s => 
      { 
       Dispatcher.Invoke(new Action(() => SetWarningStatus(WarningTypes.Warning, 
                    "Looking for backups: " + Environment.NewLine + s.Trim())), DispatcherPriority.Background); 
       test = true; 
       return; 
      })); 
    if (test) 
     break; 
} 

即使Resharperreturn是多餘這裏...

解決方案
後@狄格蘭的建議,我注意到,一直是我應該做的是改變我GetDirectories定義。

來源:

public static IEnumerable<string> GetDirectories(string root, string searchRegex, bool skipSystemDirs = false, Action<string> callback = null) {} 

要:

public delegate bool MyCallback(string s); 
public static IEnumerable<string> GetDirectories(string root, string searchRegex, bool skipSystemDirs = false, MyCallback callback = null) 

然後我可以返回一個標誌,一個回調函數內並送達裏面GetDirectories()

Btw。有趣的是,當我們將"GetDirectories"作爲二進制文件時,那麼我們可能無法在委託中停止它......我們必須等到它的執行結束。

回答

3

問題1:

您可以使用是否將由拉姆達被捕獲的變量。像:

foreach(...) 
{ 
    var stopIteration =false;  
    myObject.SomeMethod(s => 
     { 
      ... 

      stopIteration = true; //due the some condition 
     }); 

    if(stopIteration)break; 
} 

問題2:

只需使用return

myObject.SomeMethod(s => 
{ 
    //something gone wrong, or need exit; 
     return; 
}); 
+0

是的,但它是與本案有問題。我必須等待我的'SomeMethod'完成檢查條件。但是,如果我想立即打破循環呢? – Nickon

+3

@Nickon:使用這兩種技術:so set * stopIteration = true;返回; * – Tigran

+0

然後立即從lambda返回。 – Tommi