为什么需要在JS中等待AJAX​​调用,而在C#中却不需要? [英] Why do you need to await AJAX calls in JS but not in C#?

查看:89
本文介绍了为什么需要在JS中等待AJAX​​调用,而在C#中却不需要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,我习惯于使用任何库使用 await 关键字进行API调用.这样可以有效地实现承诺,并防止在下一行代码执行完毕之前执行下一行代码.

In Javascript I am used to making API calls, using whatever library, using the await keyword. This effectively implements a promise and prevents the next line of code from executing until that line of code has completed.

const response = await fetch("http://some-url.com/endpoint", { /* options */ });
const result = response.json();

这在C#中似乎不是必需的.我可以进行线程阻塞调用,而完全不使用 await ,它将不会进入下一行.

This does not seem to be necessary in C#. I can make a thread-blocking call and it won't proceed to the next line without using await at all.

var response = someApi.get("http://some-url.com/endpoint");
var str = "This line will wait for get() to complete";

更复杂的是,我看到许多C#库具有两个用于进行API调用的方法-get()和getAsync().

Further complicating things, I see many C# libraries have two methods for making an API call - get() and getAsync().

C#是否实现JS中的 await 关键字本机提供给我们的功能?那么在C#中这些 async 方法的意义是什么?我知道JS是单线程的,但是在您开始在其中创建自己的线程之前,不是每个C#控制台应用程序也都是单线程的吗?

Does C# implement the functionality that the await keyword in JS gives us natively? What then is the point of these async methods in C#? I understand JS is single thread, but isn't every C# console app also single threaded until you start making your own threads within it?

推荐答案

首先,将C#与JavaScript进行比较并不完全公平-它们是具有不同运行时和不同异步机制的不同语言.

First of all its not entirely fair to compare C# to JavaScript - they are different languages with different runtimes and different asynchronous mechanisms.

JavaScript不是多线程的-它在一个线程上运行;因此实际上不能异步执行任何操作.为了克服这个问题,JS运行时使用事件循环,该事件循环使您可以区分需要阻塞主线程的代码和不应阻塞的代码(例如和AJAX调用-一旦发送了HTTP请求,JS就无法执行任何操作)但请稍候,因此它会被扔到事件循环中,直到返回http响应为止,然后它将脱离事件循环并开始执行并执行取决于响应的代码).'async'和'await'关键字是有效的语法糖,用于包装Promise的功能:以下代码-

JavaScript is not multi-threaded - it runs on one thread; hence cant actually do anything asynchronously. To over overcome this the JS runtime makes use of the event loop which lets you differentiate between code that needs to block the main thread and code that that shouldnt block (like and AJAX call - once an http request is sent there is nothing JS can do but wait, so instead it gets thrown on the event loop until the the http response is returned, then it will get pulled off the event loop and start executing and code that depends on the response). The 'async' and 'await' keywords are effectively syntactic sugar to wrap the functionality of a Promise: the following code -

function async makeCall()
{
  const response = await makeHttpCall(httpRequest);
  console.log(response);
}

与(但不完全相同)-

function makeCall()
{
  makeHttpCall(httpRequest)
      .then(response => console.log(response));
}

一个无用的例子,它将放在事件循环中-JavaScript将调度该代码的执行,以便它看起来可以在单个线程上异步运行.

A Promise it an example of some code that will be placed on the event loop - JavaScript will schedule the execution of this code so it can run seemingly asynchronously on a single thread.

在C#中,我们实际上有许多线程可以使用,因此我们可以同时执行异步操作.为了使这一点变得更容易,C#为我们提供了任务并行库(TPL),该库将提供一系列API,使处理多线程和计划的代码执行变得更加简单.
https://docs.microsoft.com/zh-CN/dotnet/standard/parallel-programming/task-parallel-library-tpl

In C# we actually have many threads to work with so we can perform async operation at the same time. To make this easier C# gives us the Task Parallel Library (TPL) which will provide a series of APIs to make working with multi-threaded and scheduled code execution a lot simpler.
https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-parallel-library-tpl

以与JavaScript相同的方式-TPL和C#为我们提供了使用'async'和'await'关键字的相同语法糖,并且由于C#是较低级的语言,因此更多的库为开发人员提供了两种实现用于不需要阻塞当前线程或调用线程的代码.

In the same way as JavaScript - the TPL and C# gives us the same syntactic sugar for the use of the 'async' and 'await' keywords and because C# is a lower level language, more libraries provide two implementations for a developer to use for code that doesn't need to block the current or calling thread.

这将阻止所有执行,直到操作完成为止(当前和调用线程)

this will block all execution until the operation is complete (current and calling thread)

HttpResponse response = MakeHttpCall();

这将阻止当前执行线程,但将执行返回给调用线程

this will block the current thread of execution but return execution to the calling thread

 HttpResponse response = await MakeHttpCallAsync();

这将启动异步操作,但将返回一个Task以跟踪执行

this will start the async operation but will return a Task to track the execution

 Task responseTask = MakeHttpCallAsync();
 // execute code here while we wait for the http response 
 
 HttpResponse response = await responseTask; // or responseTask.Result but not ideal 

TPL(使用 Task 类型的任何C#代码)将决定是否应该创建新线程,或者是否应该使用同步上下文在当前线程上调度代码.

The TPL (any C# code using the type of Task) will decide if a new thread should be created or if the code should be scheduled on the current thread using the synchronisation context.

将C#中的 Task 类型与JS中的 Promise 类型相提并论(显然不尽相同,但有相似之处)

It also might be useful to think of the type Task in C# in a similar to the type Promise in JS (obviously not the same but there are similarities)

这篇关于为什么需要在JS中等待AJAX​​调用,而在C#中却不需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆