我在Solidworks中有几个函数,它调用一个VBA宏(通过runMacro2方法),一个同事在过去几周一直在工作。在他的代码中,他调用了Solidworks函数,在某些未知条件下,该函数挂起很长一段时间。多长时间似乎取决于身体在这个部位的大小和数量。考虑到至少有一个函数,我们想要运行这个从我自动,这只是做不到。
我尝试过使用Thread.Join(int)方法(如下所示),但它不起作用。我还尝试用相同的结果从这个答案Close a MessageBox after several seconds修改代码。在不重写整个宏的情况下,我可以在C#或VBA中处理超时吗?
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;
}发布于 2016-02-11 19:14:48
我在一个打开的文件上挂着SOLIDWORKS,也遇到了同样的问题。因此,几乎所有的引用都认为您不应该这样做,但是在这种情况下,您要么关闭它,要么永远等待。在C#中,我创建了一个callWithTimeout方法:
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);
}
}然后,挂起的代码放在这样的块中:
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();
}
}
}https://stackoverflow.com/questions/35343973
复制相似问题