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:

  1. public Task MethodName()
  2. {
  3. return Task.FromResult<object>(null);
  4. }

This doesn't work:

  1. public async Task MethodName()
  2. {
  3. return Task.FromResult<object>(null);
  4. }

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.

  1. private async Task<int> MethodName()
  2. {
  3. await SomethingAsync();
  4. return 42;//Note we return int not Task<int> and that compiles
  5. }

Sameway, When you return Task<object> your method's return type should be Task<Task<object>>

  1. public async Task<Task<object>> MethodName()
  2. {
  3. return Task.FromResult<object>(null);//This will compile
  4. }

Since your method is returning Task, it shouldn't return any value. Otherwise it won't compile.

  1. public async Task MethodName()
  2. {
  3. return;//This should work but return is redundant and also method is useless.
  4. }

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:

  1. public async Task<object> MethodName()
  2. {
  3. return await Task.FromResult<object>(null);
  4. }

Here is an example with no return value:

  1. public async Task MethodName()
  2. {
  3. await Task.CompletedTask;
  4. }

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:

  1. When you're implementing an interface that allows asynchronous callers, but your implementation is synchronous.
  2. 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>作为返回值的更多相关文章

  1. 走进Task(2):Task 的回调执行与 await

    目录 前言 Task.ContinueWith ContinueWith 的产物:ContinuationTask 额外的参数 回调的容器:TaskContinuation Task.Continue ...

  2. Task.Run(), Task.Factory.StartNew() 和 New Task() 的行为不一致分析

    重现 在 .Net5 平台下,创建一个控制台程序,注意控制台程序的Main()方法如下: static async Task Main(string[] args) 方法的主体非常简单,使用Task. ...

  3. ForkJoin有参无返回值、有参有返回值实例

    介绍: a . Fork/Join为JKD1.7引入,适用于对大量数据进行拆分成多个小任务进行计算的框架,最后把所有小任务的结果汇总合并得到最终的结果 b . 相关类 public abstract ...

  4. 使用Func<T1, T2, TResult> 委托返回匿名对象

    Func<T1, T2, TResult> 委托 封装一个具有两个参数并返回 TResult 参数指定的类型值的方法. 语法 public delegate TResult Func< ...

  5. (转)函数中使用 ajax 异步 同步 返回值错误 主函数显示返回值总是undefined -- ajax使用总结

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAloAAAE0CAIAAAB7LwoKAAAgAElEQVR4nO2dy6sc152A6+/R2mXwSn ...

  6. 写一方法用来计算1+2+3+...n,其中n作为参数输入,返回值可以由方法名返回,也可以由参数返回

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  7. C++ 需要返回值的函数却没有返回值的情况 单例模式

    昨天在看前些天写的代码,发现一个错误. #include <iostream> using namespace std; class singleton { public: static ...

  8. 根据ccid取得账户,更改某段值再创建账户,返回新的ccid

    CREATE OR REPLACE PACKAGE cux_cuxaprebate_utl IS * =============================================== * ...

  9. props default 数组/对象的默认值应当由一个工厂函数返回

    export default {props: { slides:{ type:Array, default:[] } },这是我的代码 报错是Invalid default value for pro ...

随机推荐

  1. HDU2855—Fibonacci Check-up

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2855 题目意思:求一个式子g[n]=∑C(n,k)*f[k],n很大,很明显是一个矩阵快速幂.可以打表 ...

  2. git 学习(2)--恢复版本

    查看修改历史记录 $ git log commit fba77877d316436c1b774b8933380ebcac668040 Author: keith <ustbfxx@163.com ...

  3. Photoshop打开时报错“不能打开暂存盘文件。。。”

    解决方法: 1.找到应用程序(Photoshop.exe文件) 2.右键 -> 属性 -> 兼容性 -> 更改所有用户的设置 -> 勾选上“以管理员身份运行此程序”.

  4. 并发编程 - io模型 - 总结

    1.提交任务得方式: 同步:提交完任务,等结果,执行下一个任务 异步:提交完,接着执行,异步 + 回调 异步不等结果,提交完任务,任务执行完后,会自动触发回调函数2.同步不等于阻塞: 阻塞:遇到io, ...

  5. Apache的访问控制

      目录配置段 注释不能写在指令后面,下面这样是不行的,应当换行,但为了阅读方便我就这么写了 Alias /dir/  "/var/www/html/admin"      #路径 ...

  6. Python高级特性(1):Iterators、Generators和itertools(转)

    译文:Python高级特性(1):Iterators.Generators和itertools [译注]:作为一门动态脚本语言,Python 对编程初学者而言很友好,丰富的第三方库能够给使用者带来很大 ...

  7. Python在运维工作中的经典应用之ansible

    1.安装ansible wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo curl -o /e ...

  8. 『HTML5挑战经典』是英雄就下100层-开源讲座(二)危险!英雄

    本篇为<『HTML5挑战经典』是英雄就下100层-开源讲座>第二篇,需要用到开源引擎lufylegend,可以到这里下载: 下载地址:http://lufylegend.googlecod ...

  9. 手把手教你发布自己的 Composer 包

    一.前言 Composer 是 PHP 用来管理依赖(dependency)关系的工具.我们不仅要学会使用别人提供的包,更要学会制作和分享自己的软件包,下面演示如何创建一个自己的 Composer 包 ...

  10. 转: MYSQL获取更新行的主键ID

    在某些情况下我们需要向数据表中更新一条记录的状态,然后再把它取出来,但这时如果你在更新前并没有一个确认惟一记录的主键就没有办法知道哪条记录被更新了. 举例说明下: 有一个发放新手卡的程序,设计数据库时 ...