问题描述
我们有这个方法。
异步任务< INT> AccessTheWebAsync()
{
HttpClient的客户端=新的HttpClient();
任务<字符串> getStringTask = client.GetStringAsync(http://msdn.microsoft.com);
//你可以在这里做的工作,不依赖于从GetStringAsync字符串。
DoIndependentWork();
字符串urlContents =等待getStringTask;
//问题是,这将返回一个int的方法,有任务℃的返回类型; INT>
返回urlContents.Length;
}
任务是否℃之间的隐式转换发生;>和int?如果没有,那么发生了什么,它是如何实现的工作?
都能跟得上。这只是其中的一部分如何异步
/ 等待
和
声明异步
的任何方法都必须有一个返回类型:
-
无效
(避免可能的话) -
工作
(无结果超出了完成/失败通知) -
任务< T>
(类型为T
的异步方式合乎逻辑的结果)
编译器完成所有适当的包装。问题的关键是,你的异步的返回 urlContents.Length
- 你不能使该方法只返回 INT
,因为实际的方法,当它击中的第一个计谋 EX pression将返回。因此,相反,它会返回一个任务< INT>
当异步方法本身完成,这将完成
注意等待
则正好相反 - 它的解包的一个任务< T>
到 T
的价值,这是多么此行的工作:
字符串urlContents =等待getStringTask;
...但当然解开它异步,而只是用结果
将阻塞,直到任务完成了。 (计谋
可以解开其他类型的实现awaitable格局,但任务< T>
是一个你很可能最常使用的。)
这双包装/解包就是允许异步如此组合的。例如,我可以写另一个异步方法,调用你和双打的结果是:
公共异步任务< INT> AccessTheWebAndDouble()
{
变种任务= AccessTheWeb();
INT结果=等待任务;
返回结果* 2;
}
(或简称返回等待AccessTheWeb()* 2;
课程)
We have this method.
async Task<int> AccessTheWebAsync()
{
HttpClient client = new HttpClient();
Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
// You can do work here that doesn't rely on the string from GetStringAsync.
DoIndependentWork();
string urlContents = await getStringTask;
//The thing is that this returns an int to a method that has a return type of Task<int>
return urlContents.Length;
}
Does an implicit conversion occur between Task<> and int? If not then what is happening,how is it implemented to work?
Nope. This is just part of how async
/await
works.
Any method declared as async
has to have a return type of:
void
(avoid if possible)Task
(no result beyond notification of completion/failure)Task<T>
(for a logical result of typeT
in an async manner)
The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length
- you can't make the method just return int
, as the actual method will return when it hits the first await
expression which hasn't already completed. So instead, it returns a Task<int>
which will complete when the async method itself completes.
Note that await
does the opposite - it unwraps a Task<T>
to a T
value, which is how this line works:
string urlContents = await getStringTask;
... but of course it unwraps it asynchronously, whereas just using Result
would block until the task had completed. (await
can unwrap other types which implement the awaitable pattern, but Task<T>
is the one you're likely to use most often.)
This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:
public async Task<int> AccessTheWebAndDouble()
{
var task = AccessTheWeb();
int result = await task;
return result * 2;
}
(Or simply return await AccessTheWeb() * 2;
of course.)
这篇关于如何任务&LT;诠释&GT;成为诠释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!