0

如果需要在 await 函数中显示对话框,如何处理?

例如请考虑这个 c# 伪代码:

async Task loginButton_Click(...args...)
{
    disable_some_gui_controls();

    var svc = new WebSite();

    // get captcha from user
    svc.OnCaptcha += () =>
    {
       var captcha = new CaptchaForm();
       captcha.ShowDialog(this);
       return captcha.UserCaptcha;
    }

    // login may ask captcha
    await svc.Login("user", "password");

    if (login.Success)
        enable_some_gui_controls();
}

从等待代码运行对话框会导致跨线程异常。

class WebSite
{
    public delegate string Captcha();
    public event Captcha OnCaptcha;

    public async Task<bool> Login(...args...)
    {
        ...
        if (needs captcha)
        {
           string captchaText = OnCaptcha();
           ...
        }
    }
}
4

1 回答 1

0

使用 invoke 调用主线程上的表单方法:

var captcha = new CaptchaForm();
var result = captcha.Invoke(new MethodInvoker(delegate()
{
    captcha.ShowDialog(this);
    return captcha.UserCaptcha;
}));
于 2013-10-09T09:20:49.337 回答