C# 神秘的Win32Exception:创建断点时未引发
在我的代码中发现了一个“神秘”行为。简单地说,重点是C# 神秘的Win32Exception:创建断点时未引发,c#,visual-studio-2012,C#,Visual Studio 2012,在我的代码中发现了一个“神秘”行为。简单地说,重点是 使用断点的行在没有断点的情况下不能工作 它与特权无关(不像很多关于“Win32Exception”的问题) 这里报告了一个类似的症状:。。。因为两者都与调试过程有关。(不过,我不确定这是否与我的问题有关。) 我正在给你写一个代码 以文本格式生成直方图 使用“System.Diagnostics.Process.Start”绘制生成的直方图,启动“gnuplot” 同时使用“Process.Start”(“generatedPlot.png
- 使用断点的行在没有断点的情况下不能工作
- 它与特权无关(不像很多关于“Win32Exception”的问题)
void GeneratePlot()
{
// generate a png image called 'outputPath' with console 'gnuplot.exe'
MyClass.gnuplot(dataFilePath,outputPath);
MyClass.OpenFile(outputPath);
}
OpenFile简单地定义为
static void OpenFile(string fileToOpen)
{
Process.Start(fileToOpen); // this throws 'Win32Exception' ...(*)
}
神秘的事情就在这里:为了调试这个问题,我在(*)处设置了一个断点。然后将不再抛出异常强>
(注意:由于打印图像已成功创建,因此在第二次运行时不会出现使用相同“fileToOpen”的异常。因此,请确保在调试之前删除生成的打印图像。)
当然,我设法找到了一种方法,而不是在那里设置断点。我所做的只是将MyClass.gnuplot和MyClass.OpenFile的执行分开:
void GeneratePlot()
{
// some code
MyClass.gnuplot(dataFilePath, outputPath);
}
void button1_Click(object sender, EventArgs e)
{
MyClass.OpenFile(outputPath);
}
执行“GeneratePlot()”后,点击“button1”。这次它显示了png图像
为了以防万一,我编写了这样一个代码来创建png打印图像:(它单独工作很好!)
我很好奇为什么会发生这种情况。你能给我一些建议吗?非常感谢您。在gnuplot创建和写入文件的时间与您尝试在自己的进程中打开文件的时间之间可能存在竞争条件。我敢打赌,当您在调试器中运行此命令时,在到达断点时,gnuplot进程已经关闭了输出文件,这已经足够长的时间了 要解决这个问题,您可以在发送plot命令后等待一段时间,或者更好地等待gnuplot进程退出
static void gnuplot(string dataFilePath, string outputPath)
{
Process p = new Process();
p.StartInfo.FileName = \\path\\to\\gnuplot.exe;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.WorkingDirectory = Directory.GetWorkingDirectory();
// some other StartInfo setting
p.Start();
// execute gnuplot with the following
StreamWriter sw = new StreamWriter(p.StandardInput);
sw.WriteLine("set terminal \"png\"");
sw.WriteLine("set output " + outputPath);
sw.WriteLine("plot '{0}'",dataFilePath);
// ----> wait for gnuplot to exit before returning
// (presumes that gnuplot exits shortly after executing the plot command)
p.WaitForExit();
}
如果
p.WaitForExit()代码>语句不工作(即,gnuplot进程在执行plot
命令后不退出),请尝试Thread.Sleep(TimeSpan.FromSeconds(1.0))我同意门罗的观点,这是由于比赛条件造成的。除了他推荐的方法外,我建议将您的OpenFile方法更改为:
if (System.IO.File.Exists(fileToOpen))
{
Process.Start(fileToOpen);
}
else
{
// handle missing file scenario
}
这样,如果由于任何其他原因未生成图像文件,您也将被覆盖。非常感谢<代码>p.WaitForExit()
成功了!我验证了Thread.Sleep(TimeSpan.FromSeconds(1.0)
是否有效。只是为了好玩,我还验证了我需要等待多长时间。结果是Thread.Sleep(TimeSpan.fromsecoms(200)
是阈值——等待199毫秒不起作用!非常感谢!您的代码也起作用了。也就是说,如果我在调用gnuplot进程后直接调用Process.Start(fileToOpen)
,就像我发布的那样,File.Exists(fileToOpen)
返回false
(对不起,我的“声誉”不够高,无法投票)
if (System.IO.File.Exists(fileToOpen))
{
Process.Start(fileToOpen);
}
else
{
// handle missing file scenario
}