[英]async to delay e.handled in a KeyDown event
Let's assume we have this: 假设我们有这个:
private void Input_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
}
And then i add async-await
like this: 然后我像这样添加
async-await
:
private async void Input_KeyDown(object sender, KeyEventArgs e)
{
await Task.Delay(1000);
e.Handled = true;
}
Shouldn't that do the same, but only delay it for a second? 那不应该这样做,而只是延迟一秒钟吗? So why doesn't it?
那为什么不呢?
NOTE: 注意:
I'm not seeking for debugging help, i'm just wondering why can't i use async-await
to delay handling the KeyDown
我不是在寻求调试帮助,我只是想知道为什么我不能使用
async-await
来延迟处理KeyDown
i'm just wondering why can't i use async-await to delay handling the KeyDown
我只是想知道为什么我不能使用async-await来延迟处理KeyDown
Event handlers are synchronous by definition. 根据定义,事件处理程序是同步的。 So, unless your code has a way to inform the event handler that it is acting asynchronously (eg, a WinStore-style Deferral), then it must do all "communication" (eg,
KeyEventArgs.Handled
) before its first await
. 因此,除非您的代码有办法通知事件处理程序它正在异步执行(例如WinStore风格的Deferral),否则它必须在第一次
await
之前进行所有“通信”(例如KeyEventArgs.Handled
)。
If you need to delay input in general, I recommend converting the code to use Reactive Extensions . 如果通常需要延迟输入,建议将代码转换为使用Reactive Extensions 。
The problem is that you're trying to use await in an event handler. 问题是您试图在事件处理程序中使用await。 The "synchronous part" of event handler does nothing.
事件处理程序的“同步部分”不执行任何操作。
void OnKeyDown()
{
Keys keyData = ...;
KeyEventArgs args = new KeyEventArgs(keyData);
// Thread-safe event raiser,
// equalient to KeyDown(this, args);
RaiseKeyDownEvent(args);
// Returns immediatelly when you reach
// the first await method call
bool isHandled = args.Handled;
// In the meantime event handler
// is awaiting for Task.Delay(),
// but we have already saved Handled value
}
// This code does nothing useful
private async void Input_KeyDown(object sender, KeyEventArgs e)
{
// Will return there
await Task.Delay(1000);
// The execution will be continued from there
e.Handled = true;
}
// But this code will handle input, but without any delay
private async void Input_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
await Task.Delay(1000);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.