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:

  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. 2017-2018-2 20165330实验二《Java面向对象程序设计》实验报告

    实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S.O.L.I.D原则 了解设计模式 实验步骤 (一)单元测试 三种代码 伪代码:从意图层面来解 ...

  2. win10 计算器calc命令打不开

    解决方法: 1.用管理员身份运行WindowsPowerShell: 2.用控制台命令Get-AppxPackage读取微软应用列表: 3.找到NAME那里有Windows calculator的,这 ...

  3. BBS项目部署之数据库的处理

    一  数据库的处理: 1.1上传bbs.sql(数据库中的数据) 1.2在mysql中创建bbs库,并导入数据库SQL脚本 在mysqld的文件夹中: mysql> create databas ...

  4. 10张Gif动图让你弄懂递归等概念

    图像(包括动图)是传递信息的一种高效方式,往往能增强表象.记忆与思维等方面的反应强度.所谓一图胜千言,说的就是这个道理. 今天为大家整理了十张动图GIFS,有助于认识循环.递归.二分检索等概念的具体运 ...

  5. Swift 语言附注 类型

    本页包括内容: 类型注解(Type Annotation) 类型标识符(Type Identifier) 元组类型(Tuple Type) 函数类型(Function Type) 数组类型(Array ...

  6. 创建JOB定时执行存储过程

    创建JOB定时执行存储过程有两种方式 方式1:通过plsql手动配置job,如下图: 方式2:通过sql语句,如下sql declare job_OpAutoDta pls_integer;--声明一 ...

  7. Spark源码分析之Sort-Based Shuffle读写流程

    一 .概述 我们知道Spark Shuffle机制总共有三种: 1.未优化的Hash Shuffle:每一个ShuffleMapTask都会为每一个ReducerTask创建一个单独的文件,总的文件数 ...

  8. 图层的使用要点(CALayer)

    A,图层和路径 基本图层 CALayer 动画的主角 形状图层 CAShapeLayer 绘制不规则图形 渐变图层 CAGradientLayer 颜色渐变.阴影 复制图层 CAReplicatorL ...

  9. PKU 1226 Substrings(字符串匹配+暴搜KMP模板)

    原题大意:原题链接 给出n个字符串,找出一个最长的串s,使s或者s的反转字符串(只要其中一个符合就行)同时满足是这n个串的子串. 对于样例,第一组ABCD   BCDFF  BRCD最长的串就是CD; ...

  10. [转]loadrunner:系统的平均并发用户数和并发数峰值如何估算

    一.经典公式1: 一般来说,利用以下经验公式进行估算系统的平均并发用户数和峰值数据 1)平均并发用户数为 C = nL/T 2)并发用户数峰值 C‘ = C + 3*根号C C是平均并发用户数,n是l ...