在C#中多次打开,关闭和处理文件时出现致命执行错误

时间:2013-07-06 11:05:12

标签: c# io

在一个帖子中,文件正在被连续打开,关闭和处理。这会导致问题吗?

这是代码

 StreamWriter file1 = new StreamWriter(filepath4, true);
                        for (int i = 0; i < ChannelValueForTcp; i++)
                        {
                            file1.WriteLine(data[i]);
                        }
                                file1.WriteLine(data[data.Length-1]);
                                file1.WriteLine(data[data.Length - 2]);
                                file1.Close();
                                file1.Dispose();

enter image description here

请帮助我被困住了。 (这随机出现,我们试图连续8小时运行代码。)

编辑:

不,没有其他线程可以工作或做任何与此文件相关的事情。它只在这里使用。 还有其他线程正在运行,这些线程在45分钟 - 5小时的测试后会产生相同的错误。

Here is the c code. Please download it

[DllImport("ConsoleApplication2.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern int main_c();

 public string[] tcp(string peer, int port)
        {

            int i = main_c();//the c code writes to a file called akash.txt and returns = 0 if it is successful. Then I read the file and do some functions on it. 

 if (i == 0)
            {
                StreamReader objReader = new StreamReader("akash.txt");

1 个答案:

答案 0 :(得分:2)

随机崩溃和FatalExecutionEngineError异常通常与堆栈或堆损坏相关联,这些异常可能会一直隐藏在代码中。确保使用正确的调用约定,参数类型和返回类型正确编组了所有C ++函数。

Microsoft指定消息的可能原因是:

  
    

CLR已遭到致命损坏。这通常是由数据损坏引起的,数据损坏可能是由许多问题引起的,例如调用格式错误的平台调用函数以及将无效数据传递给CLR。

  

根据您提供的代码判断,您的声明看起来是正确的,因此它可能是您编组的另一个导致问题的功能。

确保您的C ++代码稳定,而不是问题的原因。我认为它可能与删除或填充'res'缓冲区有关。

您可能正在使用一个标志来编译DLL,该标志将调用约定设置为除__cdecl之外的其他内容。您可以通过右键单击项目&gt;来验证这一点。属性&gt; C / C ++&gt;高级&gt;召集公约。