Task作为返回值以及Task<TResult>作为返回值

async await return Task

https://stackoverflow.com/questions/25191512/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

原文地址:https://www.cnblogs.com/chucklu/p/10364112.html

时间: 2024-10-08 21:27:14

Task作为返回值以及Task<TResult>作为返回值的相关文章

Task运行过程分析3——Map Task内部实现

Map Task内部实现 在Task运行过程分析2中提到,MapTask分为4种,分别是Job-setup Task.Job-cleanup Task.Task-cleanup Task和Map Task.其中,Job-setup Task和Job-cleanup Task分别是作业运行时启动的第一个任务和最后一个任务,主要工作分别是进行一些作业初始化和收尾工作,比如创建和删除作业临时输出目录:而Task-cleanup Task则是任务失败或者被杀死后,用于清理已写入临时目录中数据的任务.本文

java map按照value值来比较大小并且返回最终结果

代码下载地址:http://www.zuidaima.com/share/1830834176347136.htm 原文:java map按照value值来比较大小并且返回最终结果 package com.zuidaima.util; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class ValueComparator

MyBatis 插入时返回刚插入记录的主键值

MyBatis 插入时返回刚插入记录的主键值 一.要求: 1.数据库表中的主键是自增长的,如:id: 2.获取刚刚插入的记录的id值: 二.源代码: 1.User.java 1 package cn.com.zfc.model; 2 3 public class User { 4 5 private Integer id; 6 private String name; 7 private String password; 8 9 public Integer getId() { 10 retur

获取存储过程返回值及代码中获取返回值

获取存储过程返回值及代码中获取返回值 1.OUPUT参数返回值例: 向Order表插入一条记录,返回其标识 CREATE PROCEDURE [dbo].[nb_order_insert](@o_buyerid int ,@o_id bigint OUTPUT)ASBEGINSET NOCOUNT ON;BEGININSERT INTO [Order](o_buyerid )VALUES (@o_buyerid )SET @o_id = @@IDENTITYENDEND 存储过程中获得方法: D

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

如图检测到函数返回值总是a jQuery ajax 得到返回值 方案1:通过js回调函数获取返回值 方案2: 添加代码: async: false, 1.ajax默认是异步调用的,所以得到的返回值是空值,要得到值必须改成同步:async: false,//同步. 2.必须定义一个全局变量 var result = ""来保存返回值.否则得到的是undefined function GetReturnValue(url, jsonText) { var result = "&q

后端返回值以json的格式返回,前端以json格式接收

以随便一个类为例子:这个例子是查询企业主营类别前5事项 (1)后端将结果绑定到param中,然后将结果以为json的格式返回到前端 /** * 查询企业主营类别前5事项 * @param request * @param response * @param config * @throws Exception * @author hongxy * 2017年6月1日下午2:21:14 */ public void getEnterpriseMainCategory(HttpServletRequ

hdu 1785(You Are All Excellent)(数学函数atan2(y.x)返回(x,y)的反正切值)

You Are All Excellent Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 2945    Accepted Submission(s): 1061 Problem Description 本次集训队共有30多人参加,毫无疑问,你们都是很优秀的,但是由于参赛名额有限,只能选拔部分队员参加省赛.从学校的角度,总是希望选拔出

Java基础知识强化之集合框架笔记53:Map集合之Map集合的遍历 键值对对象找键和值

1. Map集合的遍历(键值对对象找键和值) Map -- 夫妻对  思路:  A: 获取所有结婚证的集合  B: 遍历结婚证的集合,得到每一个结婚证  C: 根据结婚证获取丈夫和妻子 转换:  A: 获取所有键值对对象的集合  B: 遍历键值对对象的集合,得到每一个键值对对象  C: 根据键值对对象获取键和值 2. 代码示例: 1 package cn.itcast_01; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 impo

UIBarButtonItem 加上返回按钮之后不可以手势返回

UIBarButtonItem 加上返回按钮之后不可以手势返回,是因为当前的手势代理不为空,需要把当前的手势代理值为nil 当前的类为 :UINavigationController self.interactivePopGestureRecognizer.delegate = nil;