请有人能够确认我是否正确理解了Async await关键字吗?(使用CTP的第3版)
到目前为止,我已经解决了在方法调用之前插入await关键字基本上做了两件事,A.它创建一个立即返回和B.它创建一个"延续",在完成异步方法调用时调用.在任何情况下,continuation都是该方法的代码块的其余部分.
所以我想知道的是,这两位代码在技术上是等价的,如果是这样,这基本上意味着await关键字与创建ContinueWith Lambda相同(即:它基本上是一个编译器快捷方式)?如果没有,有什么区别?
bool Success =
await new POP3Connector(
"mail.server.com", txtUsername.Text, txtPassword.Text).Connect();
// At this point the method will return and following code will
// only be invoked when the operation is complete(?)
MessageBox.Show(Success ? "Logged In" : "Wrong password");
Run Code Online (Sandbox Code Playgroud)
VS
(new POP3Connector(
"mail.server.com", txtUsername.Text, txtPassword.Text ).Connect())
.ContinueWith((success) =>
MessageBox.Show(success.Result ? "Logged In" : "Wrong password"));
Run Code Online (Sandbox Code Playgroud) 当我在HttpClient调用中使用async-await方法(如下例所示)时,此代码会导致死锁.用a替换async-await方法t.ContinueWith,它可以正常工作.为什么?
public class MyFilter: ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
var user = _authService.GetUserAsync(username).Result;
}
}
public class AuthService: IAuthService {
public async Task<User> GetUserAsync (string username) {
var jsonUsr = await _httpClientWrp.GetStringAsync(url).ConfigureAwait(false);
return await JsonConvert.DeserializeObjectAsync<User>(jsonUsr);
}
}
Run Code Online (Sandbox Code Playgroud)
这有效:
public class HttpClientWrapper : IHttpClient {
public Task<string> GetStringAsync(string url) {
return _client.GetStringAsync(url).ContinueWith(t => {
_log.InfoFormat("Response: {0}", url);
return t.Result;
});
}
Run Code Online (Sandbox Code Playgroud)
这段代码会死锁:
public class HttpClientWrapper : IHttpClient {
public async Task<string> GetStringAsync(string url) { …Run Code Online (Sandbox Code Playgroud) 我的目标是显示有关上传的 dll 中某些类的方法的信息。加载程序集、找到所需的类及其方法已经成功完成。现在我试图显示一个方法是否被声明为“异步”。
我发现一个线程告诉我如何做到这一点:How can I Tell if a C# method is async/await via Reflection?
不管怎样,在测试时,当我打电话时
(AsyncStateMachineAttribute)methodInfo.GetCustomAttribute(typeof(AsyncStateMachineAttribute))
我收到 System.IO.FileNotFoundException -“无法加载文件或程序集“{程序集标识符}”或其依赖项之一。系统找不到指定的文件。”。
我在一个未答复的线程中发现了此异常,但它对我没有帮助:How to Prevent MemberInfo.IsDefined from throwing FileNotFoundException on irrelevant attribute?
我知道我正在查看的方法有一个我的代码不知道的属性。我不想加载该引用,因为它只是一个测试用例,在相同的情况下可以找到许多其他不同的属性。
因此,我需要回答以下两个问题之一:
有没有办法获取属性“AsyncStateMachineAttribute”(如果存在),并忽略其他属性上的错误?
是否有另一种方法来检查方法(来自 MethodInfo)是否是异步的?
提前致谢!:)