如何等待事件点击 [英] How to await an event click

查看:90
本文介绍了如何等待事件点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试等待按下按钮时触发的回调.重要的一点是,我想等待来自简单 await 的回调而无需重新设计代码.换句话说,我要实现以下目标:

I'm trying to await a callback that is fired when a button is pressed. The important point is that I want to wait for the callback from a simple await without reshaping the code. In other words I want to achieve the following:

internal async Task BatchLogic()
{
    ProgressMessage = "Batch Logic Starts";
    await OnCallbackFired();
    ProgressMessage = "Batch Logic Ends";
}

我的尝试是

internal async Task BatchLogic()
{
    ProgressMessage = "Batch Logic Starts";
    await Task.Factory.FromAsync(beginMethod, endMethod, state);
    ProgressMessage = "Batch Logic Ends";
}

具有以下定义

 private object state = null;
 private void endMethod(IAsyncResult obj)
 {
     IsBusy = false; 
 }
 private AsyncCallback callback;
 private IAsyncResult beginMethod(AsyncCallback callback, object state)
 {
     return Task.FromResult(true);
 }

按下按钮时,将执行以下代码:

When the button is pressed, the following code is executed:

private async void RunNext()
{
    isBusy = true;
    await workToDo();
    isBusy = false; // the first 3 lines are not relevant
    callback = new AsyncCallback(endMethod);
    callback.Invoke(Task.FromResult(true));
}

问题是 endMethod 是从 callback.Invoke 调用的,但是 Factory.FromAsync 从未返回,这很可能是因为我还不了解如何使用它,也没有找到与我要实现的目标相对应的示例.

The problem is that the endMethod is called from the callback.Invoke but the Factory.FromAsync never returns, very likely because I've not understood how to use it and I've not found an example corresponding to what I'm trying to achieve.

推荐答案

这是我的初始代码的修复程序,它可以按预期工作.我必须为回调定义闭包

This is the fix for my initial code, that makes it work as expected. I had to define a closure for the callback

AsyncCallback callback;

然后我必须将 callback beginMethod 传递给闭包:

Then I had to pass the callback to the closure from the beginMethod:

private IAsyncResult beginMethod(AsyncCallback callback, object state)
{
    this.callback = callback;
    return Task.FromResult(true);
}

并最终从事件中调用它(即,用于WPF的MVVM中的 Command 方法)

and finally invoke it from the event (i.e. the Command method in the MVVM for WPF)

private async void RunNext()
{
    IsBusy = true;
    ProgressMessage = "Wait 10 seconds...";
    await workToDo();
    ProgressMessage = "Work done!";
    IsBusy = false;
    if (callback != null)
    {
        callback.Invoke(Task.FromResult(true));
    }
}

这篇关于如何等待事件点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆