是否异步调用总是创建/调用一个新的线程? [英] Does an asynchronous call always create/call a new thread?

查看:119
本文介绍了是否异步调用总是创建/调用一个新的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否异步调用总是创建一个新的线程?

Does asynchronous call always create a new thread?

例如:

如果JavaScript是单线程那么如何才能做一个异步回发?它实际上是封锁,直到它得到一个回调?如果是这样,这真的是一个异步调用?

If JavaScript is single threaded then how can it do an async postback? Is it actually blocking until it gets a callback? If so, is this really an async call?

推荐答案

这是一个有趣的问题。

异步编程是编程的范例,主要是单线程的,即继连续执行一个线程。

Asynchronous programming is a paradigm of programming that is principally single threaded, i.e. "following one thread of continuous execution".

您是指JavaScript,因此让讨论的语言,在网页浏览器的环境。 Web浏览器中运行的每个窗口JavaScript执行单一线程,它处理事件(如onclick =someFunction())和网络连接(如xmlhtt prequest调用)。

You refer to javascript, so lets discuss that language, in the environment of a web browser. A web browser runs a single thread of javascript execution in each window, it handles events (such as onclick="someFunction()") and network connections (such as xmlhttprequest calls).

<script>
function performRequest() {
  xmlhttp.open("GET", "someurl", true);
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
      alert(xmlhttp.responseText);
    }
  }
  xmlhttp.send(sometext);
}
</script>
<span onclick="performRequest()">perform request</span>

(这是一个非工作的例子,对于概念的演示只)。

(This is a nonworking example, for demonstration of concepts only).

为了以异步方式做的一切,控制线程有什么所谓的主循环。主循环看起来有点像这样:

In order to do everything in an asynchronous manner, the controlling thread has what is known as a 'main loop'. A main loop looks kind of like this:

while (true) {
    event = nextEvent(all_event_sources);
    handler = findEventHandler(event);
    handler(event);
}

要注意,这不是一个'忙循环'这是非常重要的。这有点像一个沉睡的线程,等待活动的发生。活动可能是来自用户(鼠标移动,按钮单击,打字)输入,也可以是网络活动(从服务器的响应)。

It is important to note that this is not a 'busy loop'. This is kind of like a sleeping thread, waiting for activity to occur. Activity could be input from the user (Mouse Movement, a Button Click, Typing), or it could be network activity (The response from the server).

因此​​,在上面的例子中,

So in the example above,


  1. 当跨度用户点击,就可以产生一个ButtonClicked事件,findEventHandler()将找到的span标签的on​​click事件,然后该处理程序将与事件中调用。

  2. 当创建xmlhttp的请求时,它被添加到事件源的all_event_sources列表

  3. 的performRequest()函数返回后,主循环在等待响应的nextEvent()步等待。在这一点上没有任何被​​处理的'堵'进一步的事件。

  4. 本数据来源于远程服务器后面,nextEvent()返回的网络事件,事件处理程序被发现是的onreadystatechange()方法,该方法被调用,并警告()对话框火灾了。

值得注意的是,该警报()是一个模块化的对话框。虽然这个对话框了,没有进一步的事件可以被处理。它的网页,我们有,将该网页的上下文中方框进一步执行一个现成的方法的JavaScript模型的一个偏心度。

It is worth noting that alert() is a blocking dialog. While that dialog is up, no further events can be processed. It's an eccentricity of the javascript model of web pages that we have a readily available method that will block further execution within the context of that page.

这篇关于是否异步调用总是创建/调用一个新的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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