Streamreader 和 StackOverflowException

Streamreader and StackOverflowException

分配我的 StreamReader 读取文件时,我有一个 WhosebugException,我不知道为什么会这样:(

异常详情如下:

$exception  {"Exception of type 'System.WhosebugException' was thrown."}   System.WhosebugException
+       Data    {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
        HResult -2147023895 int
        HelpLink    null    string
+       InnerException  null    System.Exception
        Message "Exception of type 'System.WhosebugException' was thrown." string
        Source  null    string
        StackTrace  null    string
        TargetSite  null    System.Reflection.MethodBase
+       Static members      
+       Non-Public members      

代码如下:

class Compile_Import
{
    public static string getargs = null;
    private static StreamReader sr;
    public static void CompileAndRun(FileInfo importInfo, string args)
    {
        getargs = args;
        if(importInfo.Extension == ".cbe" && importInfo.Exists)
        {
            sr = new StreamReader(importInfo.FullName); //Where my problem occurs.
            string curlinecont = null;
            while((curlinecont = sr.ReadLine()) != null)
            {
                string RawToken = 
             Parser.Parse.ParseLineIntoToken(Run.Stats.CurrentLineContents);
                Token_Management.Process_Token.ActOnToken(RawToken);
            }
        }
    }

我不知道这是否与你的问题有关,但是StreamReader使用静态变量意味着如果2个线程同时调用CompileAndRun,可能会出现问题.

另外,StreamReader imlements IDisposable,所以你应该调用 Dispose 或者像这样使用 using 块:

class Compile_Import
{
    public static string getargs = null;
    public static void CompileAndRun(FileInfo importInfo, string args)
    {
        getargs = args;
        if(importInfo.Extension == ".cbe" && importInfo.Exists)
        {
            using (StreamReader sr = new StreamReader(importInfo.FullName)) //Where my problem occurs.
            {
                string curlinecont = null;
                while((curlinecont = sr.ReadLine()) != null)
                {
                    string RawToken = 
                 Parser.Parse.ParseLineIntoToken(Run.Stats.CurrentLineContents);
                    Token_Management.Process_Token.ActOnToken(RawToken);
                }
            }
        }
    }

此外,这一行不应该:

string RawToken = 
    Parser.Parse.ParseLineIntoToken(Run.Stats.CurrentLineContents);

是:

string RawToken = 
    Parser.Parse.ParseLineIntoToken(curlinecont);

?否则,您不会在任何地方使用从文件中读取的行,因此读取文件毫无意义。