如何在Visual Studio宏中给出时间延迟

时间:2017-09-13 05:22:03

标签: visual-studio visual-studio-extensions visual-studio-macros

最近我更新了我的Visual Studio并开始使用扩展宏资源管理器。

我尝试使用其中一个示例宏“删除并排序所有”,但我意识到如果我有一个打开的文档,它就不会运行。所以我关闭了所有打开的文档,这次再次尝试打开所有文档并关闭它们但它也不起作用。

问题是在文档完全加载之前执行的命令。如果有一个事件或计时器可以帮助等到文档完全加载,问题就会解决。

这是我的代码。我标记了我想添加等待功能的位置:

function formatFile(file) {
    dte.ExecuteCommand("View.SolutionExplorer");
    if (file.Name.indexOf(".cs", file.Name.length - ".cs".length) !== -1) {
        file.Open();
        file.Document.Activate();

//here i want to wait for 1 second
        dte.ExecuteCommand("Edit.RemoveAndSort");

        file.Document.Save();
        file.Document.Close();
    }
}

我感谢任何帮助。

GitHub上的宏资源管理器:https://github.com/Microsoft/VS-Macros

1 个答案:

答案 0 :(得分:1)

根据您在原始帖子中分享的代码段,我还从GitHub克隆项目,您的代码应该是JavaScript代码。

在JavaScript代码中,有setTimeout()或setInterval()函数。例如,如果使用setTimeout(),则需要将暂停后需要运行的代码移动到setTimeout()回调中。

请修改您的代码,如下所示。

function formatFile(file) {
dte.ExecuteCommand("View.SolutionExplorer");
if (file.Name.indexOf(".cs", file.Name.length - ".cs".length) !== -1) {
    file.Open();
    file.Document.Activate();


    setTimeout(function () {
        //move the code that you want to run after 1 second
        dte.ExecuteCommand("Edit.RemoveAndSort");
        file.Document.Save();
        file.Document.Close();
    }, 1000);

}

在Javascript代码中有很多关于sleep()的主题。请参阅:

What is the JavaScript version of sleep()?

JavaScript sleep/wait before continuing

相关问题