2015-09-03 119 views
1

使用C#,我有方法列表(Actions)。 然后我有一个方法来调用使用foreach循环的操作。 单击按钮会调用一次又一次调用列表中的每个动作的方法。 我之后所做的是点击以每次点击只执行一个动作。 在此先感谢。C#暂停foreach循环,直到按下按钮

private static List<Action> listOfMethods= new List<Action>(); 

listOfMethods.Add(() => method1()); 
listOfMethods.Add(() => method2()); 
listOfMethods.Add(() => method3()); 
//==================================================================== 
private void invokeActions() 
{ 
    foreach (Action step in listOfMethods) 
    { 
     step.Invoke(); 
     //I want a break here, only to continue the next time the button is clicked 
    } 
} 
//==================================================================== 
private void buttonTest_Click(object sender, EventArgs e) 
    { 
     invokeActions(); 
    } 
+0

为什么选择使用'List '?你计划迭代结构多少次?是否只有一次,直到所有的方法被调用,或者你打算循环?根据你的意图,“堆栈”或“队列”可能是更好的选择。 –

+0

老实说,因为我是编程新手,并没有意识到这些:) – justlearning

回答

2

您可以添加一个计步器:

private static List<Action> listOfMethods= new List<Action>(); 
private static int stepCounter = 0; 

listOfMethods.Add(() => method1()); 
listOfMethods.Add(() => method2()); 
listOfMethods.Add(() => method3()); 
//==================================================================== 
private void invokeActions() 
{ 
     listOfMethods[stepCounter](); 

     stepCounter += 1; 
     if (stepCounter >= listOfMethods.Count) stepCounter = 0; 
} 
//==================================================================== 
private void buttonTest_Click(object sender, EventArgs e) 
    { 
     invokeActions(); 
    } 
+0

谢谢大家。我最终使用了这个解决方案。 – justlearning

1

你需要坚持按钮点击之间的一些状态,让你知道你从上次停止的位置。我建议使用一个简单的计数器:

private int _nextActionIndex = 0; 

private void buttonTest_Click(object sender, EventArgs e) 
{ 
    listOfMethods[_nextActionIndex](); 
    if (++_nextActionIndex == listOfMethods.Count) 
     _nextActionIndex = 0; // When we get to the end, loop around 
} 

该执行的第一个动作,那么接下来,每按一次按钮等。

0

先写一个方法来生成一个Task当特定Button接着按:

public static Task WhenClicked(this Button button) 
{ 
    var tcs = new TaskCompletionSource<bool>(); 
    EventHandler handler = null; 
    handler = (s, e) => 
    { 
     tcs.TrySetResult(true); 
     button.Click -= handler; 
    }; 
    button.Click += handler; 
    return tcs.Task; 
} 

然后,只需await它在你的方法,当你希望它下一个按下按钮后继续:

private async Task invokeActions() 
{ 
    foreach (Action step in listOfMethods) 
    { 
     step.Invoke(); 
     await test.WhenClicked(); 
    } 
} 
0

如果你只需要执行一次方法,我会建议将它们添加到Queue<T>,所以不需要维护状态。

private static Queue<Action> listOfMethods = new Queue<Action>(); 
listOfMethods.Enqueue(method1); 
listOfMethods.Enqueue(method2); 
listOfMethods.Enqueue(method3); 

private void buttonTest_Click(object sender, EventArgs e) { 
    if (listOfMethods.Count > 0) { 
     listOfMethods.Dequeue().Invoke(); 
    } 
}