当前位置:网站首页>同步方法中不使用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();
}
边栏推荐
- String null to empty string (what does empty string mean)
- js 获得当前时间,时间与时间戳的转换
- 单元测试,到底什么是单元测试,为什么单测这么难写
- 记给esp8266烧录刷固件
- 【杂谈】Error loading psycopg2 module :No module named psycopg2
- PTA class a 1001
- Closure of go (cumulative sum)
- Function template parameters (where are the function parameters)
- Navicat15连接本地虚拟机的Mysql(Centos7)
- INSTALL_ FAILED_ SHARED_ USER_ Incompatible error resolution
猜你喜欢
随机推荐
String null to empty string (what does empty string mean)
js翻页、kkpager.js翻页
QRcode二维码(C语言)遇到的问题
Review of database -- 1. Overview
PTA class a 1001
hx711 数据波动大的问题
数据分析入门 | kaggle泰坦尼克任务(一)—>数据加载和初步观察
【Halcon视觉】算子的结构
What is wrong about the description of function templates (how to solve link format errors)
Controller返回JSON数据
句句解析js中的完美 / 缓冲运动框架(新手专用)
[Halcon vision] morphological corrosion
【Halcon视觉】数组
Some descriptions of DS V2 push down in spark
About automatic operation on Web pages
[Halcon vision] image gray change
Use of Android grendao database
Deduct daily question 838 of a certain day
How to write a million reading article
上传图片获取宽高
![Structure of [Halcon vision] operator](/img/d9/e16ea52cea7897e3a1d61d83de472f.png)


![[Halcon vision] threshold segmentation](/img/1c/e2463a796f99804a55680b69e714a6.png)





