问题描述
我正在转换身份验证过程以支持异步,VS 2015 IDE 用以下消息警告我:异步方法缺少 'await' 运算符,将同步运行... 等等...
I am converting a authentication process to support async and the VS 2015 IDE is warning me with the following message: The async method lacks 'await' operators and will run synchronously... etc...
无论如何,代码连接到 LDAP 存储并验证用户的帐户等...我已经尝试了各种等待,但我只是在这里遗漏了一些东西.我将代码恢复到以前的状态.我将不胜感激任何指导以使其正确支持异步...
Anyway, the code connects to a LDAP store and verifies a user's account and etc... I have tried various things with await, but I am just missing something here. I put the code back to what it was before.. I would appreciate any guidance in getting it to support async correctly...
代码如下:
public async Task<User> GetAsyncADUser(PrincipalContextParameter param)
{
try
{
if (UseLDAPForIdentityServer3)
{
using (var pc = new PrincipalContext(ContextType.Domain, param.ADDomain, param.ADServerContainer, param.ADServerUser, param.ADServerUserPwd))
{
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(pc, param.UserNameToValidate);
if (userPrincipal != null)
{
bool isvalid = pc.ValidateCredentials(userPrincipal.DistinguishedName, param.UserPasswordToValidate, ContextOptions.SimpleBind);
if (isvalid)
{
User user = new User { ad_guid = userPrincipal.Guid.ToString(), Username = param.UserNameToValidate, Password = param.UserPasswordToValidate };
return user;
}
}
}
}
}
catch (Exception ex)
{
throw;
}
return null;
}
推荐答案
来自 MSDN:
以下特征总结了构成异步方法的原因:
The following characteristics summarize what makes an async method:
- 方法签名包含一个异步修饰符.
按照约定,
async
方法的名称以Async"后缀结尾.返回类型是以下类型之一:
- The method signature includes an async modifier.
The name of an
async
method, by convention, ends with an "Async" suffix. The return type is one of the following types:
Task
如果您的方法有一个返回语句,其中操作数的类型为TResult
.Task
如果你的方法没有 return 语句或有一个没有操作数的 return 语句.Void
如果您正在编写异步事件处理程序.
Task<TResult>
if your method has a return statement in which the operand has typeTResult
.Task
if your method has no return statement or has a return statement with no operand.Void
if you're writing an async event handler.
该方法通常至少包含一个等待表达式,这标志着该方法在等待的异步操作完成之前无法继续执行.同时,该方法被挂起,控制权返回给该方法的调用者.本主题的下一部分说明了在暂停点发生的情况.
The method usually includes at least one await expression, which marks a point where the method can't continue until the awaited asynchronous operation is complete. In the meantime, the method is suspended, and control returns to the method's caller. The next section of this topic illustrates what happens at the suspension point.
你可以使用 return Task.Run(() => {/* 你的代码在这里 *