简体   繁体   English

如何避免使用C#事件处理程序重复while循环?

[英]How to avoid repeated while loops with C# event handler?

In a Windows Forms application, i have a ComboBox element and need to run some code pieces periodically when ComboBox element changes. Windows窗体应用程序中,我具有ComboBox元素,并且需要在ComboBox元素更改时定期运行一些代码段。

The problem with code is, when ComboBox Text changes A to B or vice versa ,event handler triggers and previous while(true) loops are still running. 代码的问题是,当ComboBox文本从A更改为B或反之亦然时,事件处理程序触发器将触发并且先前的while(true)循环仍在运行。

When event handler is triggered, needs to run one infinite loop. 触发事件处理程序时,需要运行一个无限循环。

private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string status = comboBox.SelectedItem.ToString();

    Task.Run(async () =>
    {
        while (true)
        {
            // Running on ui thread
            datagrid.BeginInvoke((MethodInvoker)delegate
            {
                status = comboBox.SelectedItem.ToString();
            });

            if (status == "A")
            {
                Work();
            }

            else if (status == "B")
            {
                anotherWork();
            }
            else if (status == "C")
            {
                someWork();
                break;
            }

            await Task.Delay(3000);
        }
    });
}

Tried with ManualResetEvent, CancellationTokenSource, and bool check but none of them solved the problem. 尝试了ManualResetEvent,CancellationTokenSource和bool检查,但没有一个解决了问题。

What is the best practice to prevent repeated while loops? 防止重复的while循环的最佳实践是什么?

Edit: Implemented timer already but wanted to while loop trick. 编辑:已经实现了计时器,但想要while循环技巧。 I was doing bool check in a wrong way, Owen s answer is accepted. 我以错误的方式进行布尔检查,Owen的答案被接受。

Add a bool to check whether or not the loop is running: 添加一个布尔值来检查循环是否正在运行:

private bool _loopRunning;

private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    if(_loopRunning)
    {
        return;
    }

    _loopRunning = true;

    string status = comboBox.SelectedItem.ToString();

    Task.Run(async () =>
    {
        // stuff

        _loopRunning = false;
    });
}

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

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