gpt4 book ai didi

visual-studio-code - 在 vscode 扩展中订阅命令的目的?

转载 作者:行者123 更新时间:2023-12-04 19:26:18 25 4
gpt4 key购买 nike

为什么VSCode 扩展教程推荐订阅注册命令到context.subscriptions ?

据我目前所知,这似乎没有必要或有用。

这是一个 code snippet来自 VSCode 扩展 official tutorial :

let disposable = vscode.commands.registerCommand('extension.helloWorld', () => {
// The code you place here will be executed every time your command is executed

// Display a message box to the user
vscode.window.showInformationMessage('Hello World!');
});

context.subscriptions.push(disposable);

但这本身似乎工作得很好:
vscode.commands.registerCommand('extension.helloWorld', () => {
vscode.window.showInformationMessage('Hello World!');
});

此外,我尝试禁用添加和不添加注册命令的扩展 context.subscriptions -- 在这两种情况下禁用后命令都不可用。

VS Code Api Reference定义 subscriptions如:

subscriptions: {dispose}[]

An array to which disposables can be added. When this extension is deactivated the disposables will be disposed.



这是否意味着如果未处理已注册的命令,那么即使在扩展程序关闭后,它们的监听器也会以某种方式徘徊?

TDLR - 我是否应该订阅我的命令,为什么?

任何解释或见解将不胜感激!

最佳答案

是的,您应该将命令添加到 subscriptions .订阅可确保在卸载扩展程序时正确注销您的命令。
vscode.commands.registerCommand返回一个一次性对象。处理返回的对象会取消注册命令,从而允许 VS Code 清理它可能拥有的任何内部状态/句柄。

简而言之,您的扩展程序创建的所有一次性对象都应放入 subscriptions以某种方式,以便在卸载扩展程序时可以正确清理它们。 99% 的情况下,未注册一次性工具可能不会对用户造成明显问题,但在用户启用和禁用您的扩展程序而未重新启动 vscode 的情况下可能会导致问题

关于visual-studio-code - 在 vscode 扩展中订阅命令的目的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55554018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com