当前位置:网站首页>同步方法中不使用asyncTask<T> 修饰和await获取异步返回值(同步方法中调用异步方法)
同步方法中不使用asyncTask<T> 修饰和await获取异步返回值(同步方法中调用异步方法)
2022-07-26 10:29:00 【矿工学编程】
实际开发中,我们常见的异步调用就是在调用的方法上加上 async Task<T> ,具体调用异步的方法上使用 var value = await funtion(),去获取值。
常见的就是这么写。
public async Task<IActionResult> Index()
{
var client = new HttpClient(new HttpClientHandler
{
CookieContainer = new CookieContainer(),
UseCookies = true
});
var str = await client.GetStringAsync("youUrl");
return Content(str);
}
但是有时候,方法Index方法只能同步,应该怎么调用呢?其实非常简单,只要在具体需要调用的异步方法后面加.Result就可以了。
public IActionResult Index()
{
var client = new HttpClient(new HttpClientHandler
{
CookieContainer = new CookieContainer(),
UseCookies = true
});
var str = client.GetStringAsync("youUrl").Result;
return Content(str);
}
同步方法中调用异步方法(无返回值)参照:C#同步方法中调用异步方法 这篇博客
static void Main(string[] args)
{
TestAsync().Wait();
}
边栏推荐
- How to write a million reading article
- 分布式锁解决方案之Redis实现
- Function templates and non template functions with the same name cannot be overloaded (definition of overloads)
- PLC概述
- 3.1 leetcode daily question 6
- Cause: couldn‘t make a guess for 解决方法
- Android greendao数据库的使用
- The CLOB field cannot be converted when querying Damon database
- Self encapsulated database dbutils universal template
- Function template parameters (where are the function parameters)
猜你喜欢
Okaleido ecological core equity Oka, all in fusion mining mode
软件打不开了
Employee information management system based on Web
单元测试,到底什么是单元测试,为什么单测这么难写
Review of database -- 3. SQL language
【Halcon视觉】算子的结构
Cause: could't make a guess for solution
Learning about opencv (4)
Tradingview 使用教程
[Halcon vision] programming logic
随机推荐
Interview questions and answers of the first company (I)
事务的传播性propagation
Inheritance method of simplified constructor (II) - class inheritance in ES6
面试第二家公司的面试题及答案(二)
头歌 Phoenix 入门(第1关:Phoenix 安装、第2关:Phoenix 基础语法)
Study on the basis of opencv
Perfect / buffer motion framework in sentence parsing JS (for beginners)
equals与==的区别
string null转空字符串(空字符串是什么意思)
【Halcon视觉】数组
软件打不开了
PTA class a 1002
The problem of incomplete or partial display of the last recyclerview is solved
码云,正式支持 Pages 功能,可以部署静态页面
Okaleido ecological core equity Oka, all in fusion mining mode
Wechat official account release reminder (wechat official account template message interface)
简单化构造函数的继承方法(二)- ES6中的class继承
【Halcon视觉】编程逻辑
【C#语言】LINQ概述
少了个分号