Convert a method to use async(将方法转换为使用异步)
问题描述
我正在转换身份验证过程以支持异步,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
asyncmethod, 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.Taskif your method has no return statement or has a return statement with no operand.Voidif 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(() => {/* 你的代码在这里 *
本文标题为:将方法转换为使用异步
基础教程推荐
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
