簡體   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