Home > Enterprise >  How can I exit while loop with "ESC" at any time/ C#
How can I exit while loop with "ESC" at any time/ C#

Time:09-21

I have the following code in C#:

while (wechsel) 
{
    ProfDpDrv.MDPReadSlaveData(SlaveAddress, resetdiag, out dpData);
    newStatus = dpData.m_InputData[i]; 

    if (newStatus == 1) 
    {
        int debug = e.RowIndex;
        Dgv_Data_List.Rows[e.RowIndex].Cells["Adresse"].Style.BackColor = Color.Green; //
        Dgv_Data_List.Refresh();

       wechsel = false; 
    }
}

Here I want to EXIT the loop with the ESC if wechsel still at true. I have no console by the way.

CodePudding user response:

Due to the fact, that we don't know where this code is running (WinForms, WPF, ASP, etc) except it is not a console it is hard to give you a concrete help.

A general advice to solve this issue, would be to create a CancellationTokenSource and give the source.Token to the long running method. This method can within the loop regulary check, if a cancellation was requested by checking token.IsCancellationRequested and then simply do whatever needed to leave a consistent state and exit the method.

And back to the beginning of my answer, it depends on the used interface you have to hook onto something to register a keypress and then calling source.Cancel().

CodePudding user response:

I assumed that you are using WPF or WinForms.

Just subscribe to KetDown method on host window to capture all keys being pressed and then check if it's ESC and handle that appropriately, see code below:

public partial class MainWindow : Window
{
    private bool wechsel = true;

    public MainWindow()
    {
        InitializeComponent();
        this.KeyDown  = MainWindow_KeyDown;
    }

    private void MainWindow_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key != Key.Escape) return;
        wechsel = false;
        txtInfo.Text = "interrupted by ESC";
    }

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        int i = 0;
        while (wechsel)
        {
            txtInfo.Text = i  .ToString();
            await Task.Delay(500);
        }
    }
}
  • Related