当前位置:网站首页>同步方法中不使用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();
}
边栏推荐
猜你喜欢
随机推荐
About automatic operation on Web pages
INSTALL_FAILED_SHARED_USER_INCOMPATIBLE错误解决方式
【socket】三次握手是在listen中完成,accept只从完成连接的队列中拿出一个连接
PTA class a 1002
PTA class a 1001
Inheritance method of simplified constructor (II) - class inheritance in ES6
Analyze the hybrid construction objects in JS in detail (construction plus attributes, prototype plus methods)
链式方法调用的事务问题剖析
数据分析入门 | kaggle泰坦尼克任务(一)—>数据加载和初步观察
Using native JS to realize custom scroll bar (click to reach, drag to reach)
[Halcon vision] affine transformation
Li Kou daily question 917
string null转空字符串(空字符串是什么意思)
关于模板函数声明与定义的问题[通俗易懂]
【Halcon视觉】软件编程思路
The CLOB field cannot be converted when querying Damon database
Learning about tensor (III)
卸载魅族应用商店
Modelsim installation tutorial (application not installed)
String null to empty string (what does empty string mean)
![Structure of [Halcon vision] operator](/img/d9/e16ea52cea7897e3a1d61d83de472f.png)
![[Qualcomm][Network] qti服务分析](/img/76/49054ff8c7215eca98cc479ab1d986.png)







