如果需要在 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();
...
}
}
}