我有一个像这样的界面:

interface IAuthentication
{
    void AuthenticateAsync(string user, string pwhash);
    event EventHandler<AuthenticationResult> AuthenticationDone;
}


这通过在事件完成时引发事件而起作用。现在,我想将此机制包装在一个单独的阻止方法中,该方法在完成后返回身份验证结果:

AuthenticationResult Authenticate(string user, string pwhash)
{
    var auth = GetIAuthenticator();
    // ... do something
    return <the authentication result from the even argument>;
}


这有可能吗?

最佳答案

使用等待句柄,您无需检查某些标志,阻塞线程并设置超时:

private AuthenticationResult Authenticate(string user, string pwhash)
{
    IAuthentication auth = GetIAuthenticator();
    AuthenticationResult result = null;
    AutoResetEvent waitHangle = new AutoResetEvent(false);

    auth.AuthenticationDone += (o, e) =>
        {
            result = e;
            waitHangle.Set();
        };

    auth.AuthenticateAsync(user, pwhash);
    waitHangle.WaitOne(); // or waitHangle.WaitOne(interval);
    return result;
}

10-04 12:14
查看更多