繁体   English   中英

C#暂停foreach循环,直到按下按钮

[英]C# pause foreach loop until button pressed

使用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();
    }

您可以添加一个计步器:

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();
    }

您需要在两次单击之间保持某种状态,以便您知道上次退出的位置。 我建议使用一个简单的计数器:

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
}

每次按下该按钮时,将执行第一个动作,然后执行下一个动作,等等。

首先编写一个在下次按下特定Button时生成Task的方法:

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();
    }
}

如果您只需要执行一次方法,则建议将它们添加到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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM