Architecture problem
I want to do a method that will replace this-
for (var i = 0; i < seconds; i++)
{
...... // code that should run every second
Thread.Sleep(1000);
}
So I wrote the following method:
public static void DoEverySecond(int seconds, Action action)
{
for (var i = 0; i < seconds; i++)
{
action.Invoke();
Thread.Sleep(1000);
}
}
and now every time that I want to do something every second I can just call -
HelperClass.DoEverySecond(5, () =>
{
Console.Write("Hellow")
});
the problem is that when the action contains return, the loop doesn't stop. It's just getting out from the action and continues开发者_如何学Go to the next iteration.
HelperClass.DoEverySecond(5, () =>
{
return;
});
Have you considered Func instead of Action and then change your code to something like:
public static void DoEverySecond(int seconds, Func<bool> action)
{
for (var i = 0; i < seconds; i++)
{
if(!action.Invoke())
{
return;
}
Thread.Sleep(1000);
}
}
And then have your function return false if your loop should break
I prefer @userx's solution.
However, another option would be to throw an exception inside the invoked action when you want to exit the loop. Catch the exception in DoEverySecond
and break
out of the loop. Be aware of the performance implications of doing this if it is a common occurrence.
Problem is not in the c#, but in your code.
Of course, them the action returns, next lines of code woudn't execute.
You should rewrite your code to no use of return statement:
HelperClass.DoEverySecond(5, () =>
{
bool notReturn = true;
// some code to define, return or not
if (notReturn)
// some other code here
});
精彩评论