首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Solidworks宏的C#超时

Solidworks宏的C#超时
EN

Stack Overflow用户
提问于 2016-02-11 15:54:53
回答 1查看 556关注 0票数 2

我在Solidworks中有几个函数,它调用一个VBA宏(通过runMacro2方法),一个同事在过去几周一直在工作。在他的代码中,他调用了Solidworks函数,在某些未知条件下,该函数挂起很长一段时间。多长时间似乎取决于身体在这个部位的大小和数量。考虑到至少有一个函数,我们想要运行这个从我自动,这只是做不到。

我尝试过使用Thread.Join(int)方法(如下所示),但它不起作用。我还尝试用相同的结果从这个答案Close a MessageBox after several seconds修改代码。在不重写整个宏的情况下,我可以在C#或VBA中处理超时吗?

代码语言:javascript
复制
    public void runBB()
    {
        Stopwatch testStop = new Stopwatch();
        Thread workerThread = new Thread(bbRun);
        testStop.Start();
        workerThread.Start();
        if (!workerThread.Join(50))
        {
            workerThread.Abort();
            testStop.Stop();
            MessageBox.Show("Unable to generate Bounding Box after " + testStop.ElapsedMilliseconds/1000 + " seconds. Please enter data manually.", "Solidworks Derped Error.");
        }
        return;

    }//Still uses Macro (2-5-16)
    public static void bbRun()
    {
        iSwApp.RunMacro2(macroPath + "BOUNDING_BOX.swp", "test11", "main", 0, out runMacroError);
        return;
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-11 19:14:48

我在一个打开的文件上挂着SOLIDWORKS,也遇到了同样的问题。因此,几乎所有的引用都认为您不应该这样做,但是在这种情况下,您要么关闭它,要么永远等待。在C#中,我创建了一个callWithTimeout方法:

代码语言:javascript
复制
    private void callWithTimeout(Action action, int timeoutMilliseconds, String errorText) {
        Thread threadToKill = null;
        Action wrappedAction = () =>
        {
            threadToKill = Thread.CurrentThread;
            action();
        };

        IAsyncResult result = wrappedAction.BeginInvoke(null, null);
        if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) {
            wrappedAction.EndInvoke(result);
        } else {
            threadToKill.Abort();
            throw new TimeoutException(errorText);
        }
    }

然后,挂起的代码放在这样的块中:

代码语言:javascript
复制
bool timedOut = false;
try {
    callWithTimeout(delegate() {
        // code that hangs here
    }, 60000, "Operation timed out.  SOLIDWORKS could not open the file.  This file will be processed later.");
} catch (TimeoutException){
    timedOut = true;
} finally {
    if(timedOut) {
        Process[] prs = Process.GetProcesses();
        foreach (Process p in prs) {
            if (p?.ProcessName.Equals("SLDWORKS") ?? false)
                p?.Kill();
        }
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35343973

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档