在镖异步编程 [英] async programming in dart

查看:122
本文介绍了在镖异步编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有关Java作为要怎么做线程/异步。我用新的Thread(目标)。开始(),其中的目标是可执行的,做线程在java中的一种方式。新的并发API有替代品,但我们知道,在特定的呼叫新主题创建,并在任务执行通过。

I am relating to java as to how to do thread/async. I use new Thread(target).start() where target is Runnable as one way to do threading in java. New concurrent api has alternatives but we know that on specific call new threads are creating and passed in tasks are executed.

同样如何在异步达特做了什么?
我读发送/ receivport,完成者/未来,spawnFunction。对我来说,只有spawnFunction是有说服力的语句,将创建新的线程。可以解释如何完成者/未来帮助。我知道他们需要回调,但有没有在JavaScript的一些隐含的逻辑/规则/镖的回调总是在不同的线程中执行。

Similarly how is async done in Dart ? I read on send/receivport, completer/future, spawnFunction. To me only spawnFunction is convincing statement that will create new thread. can one explain how completer/future help. i know they take callbacks but is there some implicit logic/rule in javascript/dart that callbacks always be execute in different thread.

下面是镖片段/伪code:

below is dart snippet/pseudo code:

void callback() {
  print("callback called");
}

costlyQuery(sql, void f()) {
  executeSql(sql);
  f();
}

costlyQuery("select * from dual", callback);

我希望我的costlyQuery签名取函数作为第二个参数是正确的。所以现在我不认为 F()的ExecuteSQL(SQL)将是异步。可能会采取上面的例子添加完成者/将来如果可以使异步帮助我理解了。

I hope my costlyQuery signature to take function as 2nd parameter is correct. so now I do not think that f() after executeSql(sql) is going to be async. may be taking above example add completer/future if that can make async to help me understand.

推荐答案

TL;博士:没有隐含的规则,即回调将不会阻止

tl;dr: There is no implicit rule that a callback will not block.

在Javascript中,有没有线程(除了WebWorkers,但这是不同的)。这意味着,如果你的code组中的任何一部分,整个应用程序将被阻止。没有什么神奇的有关回调,也只是功能:

In Javascript, there are no threads (except WebWorkers, but that's different). This means that if any part of your code blocks, the whole application is blocked. There is nothing magic about callbacks, they are just functions:

function longLoop(cb) {
    var i = 1000000;
    while (i--) ;
    cb();
}

function callback() {
    console.log("Hello world");
}

function fun() {
    longLoop(callback);
    console.log("Called after Hello World is printed");
}

为使一些异步,回调必须在事件队列中,只通过一些API调用发生放


  • 用户启动的事件handlers-点击,键盘,鼠标

  • API事件handlers- XmlHTT prequest回调,WebWorker通信

  • 职能 - setTimeout的定时,setInterval的

    • user initiated event handlers- clicks, keyboard, mouse
    • API event handlers- XmlHTTPRequest callbacks, WebWorker communication
    • timing functions- setTimeout, setInterval

    当事件触发,回调被放置在事件队列时,所有其他的回调已经完成执行执行。这意味着没有两行的 code都不会在同一时间被执行。

    When the event is triggered, the callback is placed on the event queue to be executed when all other callbacks have finished executing. This means that no two lines of your code will ever be executing at the same time.

    我假设你已经至少在这个职位有关期货的。如果不是,这是一个良好的阅读,并从马口直来了。

    I assume you have at least stumbled on this post about futures. If not, it's a good read and comes straight from the horses mouth.

    在Javascript中,你必须做一些工作,使异步code感。甚至还有一个Javascript库称为期货的做常用的东西,如异步循环和序列(全面披露,我曾亲自与合作这个库的作者)。

    In Javascript, you have to do some work to make sense of asynchronous code. There's even a Javascript library called futures for doing common things, such as asynchronous loops and sequences (full disclosure, I have personally worked with the author of this library).

    未来的概念是由函数创造未来,未来将在某个时候在路上完成作出了承诺。如果您打算做一些异步调用,开创未来,归还,并履行承诺时,异步调用完成。从博客文章:

    The notion of a future is a promise made by the function creating the future that the future will be completed at some point down the road. If you are going to make some asynchronous call, create a future, return it, and fulfill the promise when the asynchronous call finishes. From the blog post:

    Future<Results> costlyQuery() {
        var completer = new Completer();
    
        database.query("SELECT * FROM giant_table", (results) {
            // when complete
            completer.complete(results);
        });
    
        // this returns essentially immediately,
        // before query is finished
        return completer.future; 
    }
    

    如果database.query是一个阻塞调用,未来将立即完成。此示例假定 database.query 是一个非阻塞调用(异步),因此未来该功能退出后实现。 completer.complete 将调用一切功能传递给 completer.then()的参数中指定。

    If database.query is a blocking call, the future will be completed immediately. This example assumes that database.query is a non-blocking call (async), so the future will be fulfilled after this function exits. completer.complete will call whatever function is passed to completer.then() with the arguments specified.

    您例如,修改为成语和异步:

    Your example, modified to be idiomatic and asynchronous:

    void callback() {
      print("callback called");
    }
    
    costlyQuery(sql) {
      var completer = new Completer();
      executeSql(sql, () => completer.complete());
      return completer.future;
    }
    
    costlyQuery("select * from dual").then(callback);
    

    这是异步的,正确地使用期货。你可以通过你自己的回调函数到 costlyQuery 为你做,并呼吁在回调的ExecuteSQL 来实现同样的事情,但就是这样做的JavaScript的方式,而不是飞镖的方式。

    This is asynchronous and uses futures correctly. You could pass your own callback function into costlyQuery as you have done and call that in the callback to executeSql to achieve the same thing, but that is the Javascript way of doing it, not the Dart way.

    株类似于Java的线程,但分离是一个并发模型和线程是并行模型(参见<一个href=\"http://stackoverflow.com/questions/1050222/concurrency-vs-parallelism-what-is-the-difference\">this SO质疑约并发VS并行)的详细信息。

    Isolates are similar to Java's threads, except that isolates are a concurrency model and threads are a parallelism model (see this SO question for more information about concurrency vs parallelism).

    飞镖是该规范特别并不要求一切都在一个单独的线程中运行。它仅强制要求不同执行上下文不具有访问相同的数据。每个隔离都有自己的记忆,只能通信(例如发送数据)与其他菌株通过发送/接收端口。

    Dart is special in that the specification does not mandate that everything be run in a single thread. It only mandates that different executing contexts do not have access to the same data. Each isolate has it's own memory and can only communicate (e.g. send data) with other isolates through send/receive ports.

    这些端口的工作方式类似于围棋频道,如果你熟悉了。

    These ports work similarly to channels in Go if you're familiar.

    这是分离是独立于其他code的运行的隔离执行环境。在Javascript而言,这意味着它具有它自己的事件队列。见<一href=\"http://www.dartlang.org/docs/dart-up-and-running/ch03.html#ch03-dartisolate---concurrency-with-isolates\">the达特旅游一个更完整的介绍株。

    An isolate is an isolated execution context that runs independently of other code. In Javascript terms, this means that it has it's own event queue. See the Dart tour for a more complete introduction to isolates.

    让我们说你的ExecuteSQL是阻塞函数。如果我们不想等待它完成,我们可以将其加载到一个隔离:

    Lets say your executeSql is a blocking function. If we don't want to wait for it to finish, we could load it into an isolate:

    void callback() {
        print("callback called");
    }
    
    void costlyQuery() {
        port.receive((sql, reply) {
            executeSql(sql);
            reply.send();
        });
    }
    
    main() {
        var sendPort = spawnFunction(costlyQuery);
    
        // .call does all the magic needed to communicate both directions
        sendPort.call("select * from dual").then(callback);
    
        print("Called before executeSql finishes");
    }
    

    这code创建一个分离,将数据发送到它然后注册时,它的完成回调。即使的ExecuteSQL 块,的main()不一定会阻塞。

    This code creates an isolate, sends data to it then registers a callback for when it's done. Even if executeSql blocks, main() will not necessarily block.

    这篇关于在镖异步编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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