Task作为返回值以及Task<TResult>作为返回值
async await return Task
Can somebody explain what does this means into a synchronous method? If I try to change the method to async then VS complain about it.
This works:
public Task MethodName()
{
return Task.FromResult<object>(null);
}
This doesn't work:
public async Task MethodName()
{
return Task.FromResult<object>(null);
}
So basically I would like to know what exactly this means: Task.FromResult<object>(null);
解答1
async methods are different than normal methods. Whatever you return from async methods are wrapped in a Task.
If you return no value(void) it will be wrapped in Task, If you return int it will be wrapped in Task<int> and so on.
If your async method needs to return int you'd mark the return type of the method as Task<int> and you'll return plain int not the Task<int>. Compiler will convert the int to Task<int> for you.
private async Task<int> MethodName()
{
await SomethingAsync();
return 42;//Note we return int not Task<int> and that compiles
}
Sameway, When you return Task<object> your method's return type should be Task<Task<object>>
public async Task<Task<object>> MethodName()
{
return Task.FromResult<object>(null);//This will compile
}
Since your method is returning Task, it shouldn't return any value. Otherwise it won't compile.
public async Task MethodName()
{
return;//This should work but return is redundant and also method is useless.
}
Keep in mind that async method without an await statement is not async.
解答2
You need to use the await keyword when use async and your function return type should be generic Here is an example with return value:
public async Task<object> MethodName()
{
return await Task.FromResult<object>(null);
}
Here is an example with no return value:
public async Task MethodName()
{
await Task.CompletedTask;
}
Read these:
TPL: http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx and Tasks: http://msdn.microsoft.com/en-us/library/system.threading.tasks(v=vs.110).aspx
Async: http://msdn.microsoft.com/en-us/library/hh156513.aspx Await: http://msdn.microsoft.com/en-us/library/hh156528.aspx
What is the use for Task.FromResult<TResult> in C#
In C# and TPL (Task Parallel Library), the Task class represents an ongoing work that produces a value of type T.
I'd like to know what is the need for the Task.FromResult method ?
That is: In a scenario where you already have the produced value at hand, what is the need to wrap it back into a Task?
The only thing that comes to mind is that it's used as some adapter for other methods accepting a Task instance.
解答1
There are two common use cases I've found:
- When you're implementing an interface that allows asynchronous callers, but your implementation is synchronous.
- When you're stubbing/mocking asynchronous code for testing.
解答2
One example would be a method that makes use of a cache. If the result is already computed, you can return a completed task with the value (using Task.FromResult). If it is not, then you go ahead and return a task representing ongoing work.
Cache Example: Cache Example using Task.FromResult for Pre-computed values
Task作为返回值以及Task<TResult>作为返回值的更多相关文章
- 走进Task(2):Task 的回调执行与 await
目录 前言 Task.ContinueWith ContinueWith 的产物:ContinuationTask 额外的参数 回调的容器:TaskContinuation Task.Continue ...
- Task.Run(), Task.Factory.StartNew() 和 New Task() 的行为不一致分析
重现 在 .Net5 平台下,创建一个控制台程序,注意控制台程序的Main()方法如下: static async Task Main(string[] args) 方法的主体非常简单,使用Task. ...
- ForkJoin有参无返回值、有参有返回值实例
介绍: a . Fork/Join为JKD1.7引入,适用于对大量数据进行拆分成多个小任务进行计算的框架,最后把所有小任务的结果汇总合并得到最终的结果 b . 相关类 public abstract ...
- 使用Func<T1, T2, TResult> 委托返回匿名对象
Func<T1, T2, TResult> 委托 封装一个具有两个参数并返回 TResult 参数指定的类型值的方法. 语法 public delegate TResult Func< ...
- (转)函数中使用 ajax 异步 同步 返回值错误 主函数显示返回值总是undefined -- ajax使用总结
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAloAAAE0CAIAAAB7LwoKAAAgAElEQVR4nO2dy6sc152A6+/R2mXwSn ...
- 写一方法用来计算1+2+3+...n,其中n作为参数输入,返回值可以由方法名返回,也可以由参数返回
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- C++ 需要返回值的函数却没有返回值的情况 单例模式
昨天在看前些天写的代码,发现一个错误. #include <iostream> using namespace std; class singleton { public: static ...
- 根据ccid取得账户,更改某段值再创建账户,返回新的ccid
CREATE OR REPLACE PACKAGE cux_cuxaprebate_utl IS * =============================================== * ...
- props default 数组/对象的默认值应当由一个工厂函数返回
export default {props: { slides:{ type:Array, default:[] } },这是我的代码 报错是Invalid default value for pro ...
随机推荐
- TCP implements its own acknowledgment scheme to guarantee successful data delivery
wTCP本身已经确保传输的成功性. HTTP The Definitive Guide 4.2.4 Delayed Acknowledgments Because the Internet itsel ...
- Zipline入门教程
Zipline Beginner Tutorial Basics 基础 Zipline is an open-source algorithmic trading simulator written ...
- Elasticsearch提示low disk watermark [85%] exceeded on [UTyrLH40Q9uIzHzX-yMFXg][Sonofelice][/Users/baidu/Documents/work/soft/data/nodes/0] free: 15.2gb[13.4%], replicas will not be assigned to this node
mac本地启动es之后发现运行一段时间一分钟就能打印好几条info日志: [--13T10::,][INFO ][o.e.c.r.a.DiskThresholdMonitor] [Sonofelice ...
- Linux文件操作相关命令
1.创建文件夹: [root@izuf6ih01h8fzeziddwkfdz sm]# mkdir a 创建一个名为a的文件夹 2.创建文件: [root@izuf6ih01h8fzeziddwkfd ...
- springmvc 之 easyUI开发商城管理系统
1.分页 url:controller的路径 pageSize:每页显示的行数 ---后台参数名(rows) 会向后台传递一个 page参数,表示当前页.---后台参数名(page) controll ...
- macOS 上安装 PECL
一.简介 PECL(The PHP Extension Community Library)是 PHP 扩展的存储库,为 PHP 所有的扩展提供提供托管和下载服务. 通过 PEAR(PHP Exten ...
- 测试CDockablePane。 测试他的最基本的功能。
最近看到一句话: ××××××××××××××××××××××××××××××××××××××××××× CDockablePane是一个通用窗口容器,它主要有两个用途:在一个框架中悬浮或者停靠窗口. ...
- co.js异步回调原理理解
co.js是基于es6的generator实现的,相当于generator函数的一个自动执行器 generator的简单介绍 function* fn(){ before() yield firstY ...
- AngularJS 笔记系列(五)过滤器 filter
过滤器是用来格式化给用户展示的数据的. 在 HTML 中的模板绑定符号{{}} 内通过|符号来调用过滤器. 大写:{{ name | uppercase }} 也可以在 JS 中进行调用$filter ...
- Mac下的Mysql无法登陆的问题
以下是还原root权限和更改root密码的最便捷方法. 1:装mysql workbench .可视化界面直接操作. 2:苹果->系统偏好设置->最下边点mysql 在弹出页面中 关闭my ...