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 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
