在GNOME扩展中运行异步函数

问题描述 投票:0回答:1

我想在GNOME扩展内运行循环。在DBus服务方法调用之后,但是gnome shell冻结

[我了解到extensions run in the GLib's Main Loop和我应该使用GTask API,但我找不到使用它的方法,也没有明确的示例。

我想我不能使用GLib.spawn_async_with_pipes,因为我不想调用命令,而是同一类中的函数

代码示例:

class Foo {

  constructor () {
    this._ownName()
  }
  
  _ownName () {
    Gio.bus_own_name(
      Gio.BusType.SESSION,
      'net.foo',
       Gio.BusNameOwnerFlags.NONE,
      this._onBusAcquired.bind(this),
      this._noOp,
      this._noOp
    )
  }

  _onBusAcquired(connection) {
    connection.register_object(
    '/net/foo',
    GioInterface,
    this._methodCallClosure.bind(this),
    this._noOp,
    this._noOp
  )
  
  _methodCallClosure(connection, sender, objectPath, interfaceName,
                     methodName, parameters, invocation) {
    this._listen = true
    this._runLoop()

    invocation.return_value(null)
  }

  // this function should not block GLib's Main Loop
  _runLoop () {
    while(this._listen) {
      ...
    }
  }
}
javascript asynchronous gnome gnome-shell-extensions gjs
1个回答
0
投票

可能有很多方法可以避免阻塞主循环,但是最好的方法取决于哪个事件将导致中断while循环。

如果您确实需要“轮询”某些条件,我认为最简单的方法可能是超时循环:

function myPollingFunc(arg1, arg2) {
    if (the_event_occured) {
        // Here is where you will invoke whatever it is you want to do
        // when the event occurs, then destroy the source since the
        // condition has been met.
        this.classMethod(arg1, arg2);

        return GLib.SOURCE_REMOVE;
    }

    // If the condition was not met, you can wait until the next loop and
    // check again.
    return GLib.SOURCE_CONTINUE;
}

// Probably you'll want to store this ID (maybe as a property on your class),
// so you can destroy the source if the DBus service is destroyed before the
// event you're waiting for occurs.
let sourceId;

sourceId = GLib.timeout_add_seconds(
    // Generally this priority is fine, but you may choose another lower one
    // if that makes sense
    GLib.PRIORITY_DEFAULT,

    // The timeout interval of your loop. As described in the linked article,
    // second-based loops tend to be a better choice in terms of performance,
    // however note that at least one interval will pass before the callback
    // is invoked.
    1,

    // Your callback function. Since you're probably creating the source from
    // a class method and intend on modifying some internal state of your class
    // you can bind the function to the class scope, making it's internal state
    // and other methods available to your callback.
    //
    // Function.bind() also allows you to prepend arguments to the callback, if
    // that's necessary or a better choice. As noted above, you'll probably want
    // to store the ID, which is especially important if you bind the callback to
    // `this`.
    // 
    // The reason is that the callback will hold a reference to the object it's
    // bound to (`this` === `Foo`), and the source will hold the callback in the
    // loop. So if you lose track of the source and the ability to destroy it, the
    // object will never be garbage collected.
    myPollingFunc.bind(this, arg1, arg2)
);

您可以对一个空闲源执行相同的操作,该源将等待直到没有更高优先级的事件挂起,而不是固定的超时。空闲源的问题在于,如果没有其他未决事件,则您的回调将几乎以while循环的速度被重复调用,并且您可能会饿死主循环(例如,使其他事件难以获得)一只脚踩在门上。

另一方面,如果您实际上不需要轮询条件,而是在等待信号发出或GObject属性更改,则可能会有更直接的方法:

...

  _runLoop () {
    // Waiting for some object to emit a signal or change a property
    let handlerId = someObject.connect('some-signal', () => {
        someObject.disconnect(handlerId);

        this.classMethod(arg1, arg2);
    });

    let propId = someGObject.connect('notify::some-prop', () => {
        if (someGObject.some_prop === 'expected_value') {
            someGObject.disconnect(propId);

            this.classMethod(arg1, arg2);
        }
    });
  }

...

[不知道您正在等待什么类型的事件或条件,很难为最佳解决方案提供更好的建议,但这也许会有所帮助。我通常会说,如果您认为要在某些条件下循环,那么最好在现有GLib主循环中检查该条件,而不要创建自己的子循环。

编辑

[具有更多上下文,似乎您将要依赖一种或另一种方式依赖外部过程。在这种情况下,我强烈建议您避免使用GLib中的较低级别的生成函数,而应使用GSubprocess。

对于高级语言绑定,这是一个更安全的选择,并且还包括用C编写的帮助程序函数,无论如何您最终都可能会重写它们:

onProcExited(proc, result) {
    try {
        proc.wait_check_finish(proc, result);
    } catch (e) {
        logError(e);
    }
}

onLineRead(stdout, result) {
    try {
        let line = stdout.read_line_finish_utf8(result)[0];

        // %null generally means end of stream
        if (line !== null) {
            // Here you can do whatever processing on the line
            // you need to do, and this will be non-blocking as
            // all the I/O was done in a thread.
            someFunc(line);

            // Now you can request the next line
            stdout.read_line_async(null, onLineRead.bind(this));
        }
    } catch (e) {
        logError(e);
    }
}

startFunc() {
    this._proc = new Gio.Subprocess({
        argv: ['proc_name', '--switch', 'arg', 'etc'],
        flags: Gio.SubprocessFlags.STDOUT_PIPE
    });
    this._proc.init(null);

    // Get the stdout pipe and wrap it in a buffered stream
    // with some useful helpers
    let stdout = new Gio.DataInputStream({
        base_stream: this._proc.get_stdout_pipe()
    });

    // This function will spawn dedicated a thread, reading and buffering
    // bytes until it finds a line ending and then invoke onLineRead() in
    // in the main thread.
    stdout.read_line_async(
        GLib.PRIORITY_DEFAULT,
        null // Cancellable, if you want it
        onLineRead.bind(this)
    );

    // Check the process completion
    this._proc.wait_check_async(null, onProcExited.bind(this));
}

编写这样的递归读取循环非常简单,GTask函数(*_async() / *_finish())会为您安排主循环中的回调。所有I / O都是在专用线程中完成的,因此您处理输出的工作都是非阻塞的。

当您最终放弃对this._proc的引用时,可以确保正确清理了所有管道和资源,避免晃来晃去的文件描述符,僵尸进程等。如果您需要提早退出流程,可以随时致电Gio.Subprocess.force_exit()。读取循环本身将在stdout管道包装器上保留一个引用,因此您可以将其保留以完成其工作。

© www.soinside.com 2019 - 2024. All rights reserved.