Reputation: 10146
Question 1. I wonder if it's possible to stop the loop in the inside operation's callback?
Question 2. Can I stop SomeMethod()
in the callback?
E.g. I have a code like:
foreach(...)
{
myObject.SomeMethod(s =>
{
// something break-like here to stop foreach/method?
});
}
[edit]
Here's the example of the code I use - it doesn't work as I want.
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;
}
Even Resharper
says that return
is redundant here...
Solution
After @Tigran's suggestion I noticed that always what I should do is to change my GetDirectories
definition.
From:
public static IEnumerable<string> GetDirectories(string root, string searchRegex, bool skipSystemDirs = false, Action<string> callback = null) {}
To:
public delegate bool MyCallback(string s);
public static IEnumerable<string> GetDirectories(string root, string searchRegex, bool skipSystemDirs = false, MyCallback callback = null)
Then I can return a flag inside a callback function and serve it inside GetDirectories()
.
Btw. what's interesting, when we have our "GetDirectories"
as a binary, then we probably can't stop it in delegate... We have to wait until its execution finishes.
Upvotes: 0
Views: 1211
Reputation: 62248
Question 1:
You can if use the variable which will be captured by lambda. Like:
foreach(...)
{
var stopIteration =false;
myObject.SomeMethod(s =>
{
...
stopIteration = true; //due the some condition
});
if(stopIteration)break;
}
Question 2:
Just use return
myObject.SomeMethod(s =>
{
//something gone wrong, or need exit;
return;
});
Upvotes: 3