在需要的循环中调用Application.DoEvents()的替代方法

时间:2014-03-27 09:18:26

标签: c# multithreading doevents

下面的c#代码绝不是理想的,我真的只是在寻求建议和建议,以便我能够最好地重构这些并使代码更安全。

基本上有一个类变量存储安全检查阶段值(初始化为0)。按下我的应用程序中的按钮时,将运行以下代码以检查用户是否有权访问其帐户屏幕。根据方法参数,调用适当的处理程序方法,该方法向用户显示PIN条目用户控件(此用户控件是显示为全屏和最顶层的自定义控件)。处理程序代码正在运行时,下面显示的代码在do while循环中调用Application.DoEvents,以便在用户输入其PIN时保持响应。如果do while循环不存在,则在我们有机会确认用户PIN正确之前,用户尝试访问的屏幕将显示在PIN输入屏幕的顶部。当PIN条目通过时,安全检查阶段变量设置为1,允许显示帐户屏幕。

            try
            {
                this.Cursor = Cursors.WaitCursor;

                Application.DoEvents();

                SecurityCheckStage = 0;

                Security             = new tskSecurity(true);
                Security.TaskUpdate += new TaskUpdateHandler(_handler);

                TaskManager.AddTask(Security, true);

                this.Cursor = Cursors.Default;

                // Wait until security check has passed before showing account screen
                do
                {
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(100);
                }
                while (SecurityCheckStage == 0);

                if (SecurityCheckStage == 1) ShowAccountScreen();

                return false;
            }
            catch
            {
                throw;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

我知道在循环中调用Application.DoEvents()并不是一个好习惯,所以我真的想重做这段代码以使其更好。

非常感谢任何帮助。请记住,问题的解决方案必须与.NET 3.5 Framework一起使用。

1 个答案:

答案 0 :(得分:0)

使用System.Windows.Forms.Timer ...例如:

//...

    timer.Tick += TimerEventProcessor;
    timer.Start();
//..
private void TimerEventProcessor(Object sender, EventArgs myEventArgs)
{
    if (SecurityCheckStage == 1)
    {
        var timer = (Timer) sender;
        timer.Stop();
        ShowAccountScreen();
    }
}
相关问题