替代wpf中的Application.DoEvents()

时间:2013-09-25 14:09:37

标签: c# wpf

我有以下情况

kl.KeyDown += CheckPwd;
while(flag)
   System.Windows.Forms.Application.DoEvents();

//continue other code based on "Success"

//This will be called for every keydown
void CheckPwd(object sender, KeyEventArgs e)
{
   //some code here
   if(....)
   {
       flag = true;
       Success = true;   
       kl.KeyDown -= CheckPwd;   
   }
   else
   {
       flag = true;
       Success = false;
       kl.KeyDown -= CheckPwd;
   }
}

我希望避免使用Application.DoEvents()。我尝试使用ManualResetEvent,但是当我调用WaitOne()时,它会阻止当前线程,并导致此问题,CheckPwd未启动。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

创建一个新的Success事件,当您达到成功条件时触发它,然后在该事件的事件处理程序中将您需要执行的代码放在Success上:

定义事件:

public event Action Success;

附加处理程序:

kl.KeyDown += CheckPwd;
Success += DoSuccessStuff;

解雇活动:

void CheckPwd(object sender, KeyEventArgs e)
{
   //some code here
   if(...)
   {
       flag = true;
       Success = true;   
       kl.KeyDown -= CheckPwd;   
       if(Success != null) Success();
   }
   //...