C# 读写 TextFile 在中间结束

C# Read Write TextFile End In The Middle

我运行一个方法,一共三部分,第一部分和第三部分都一样"read text file",

第二部分是将字符串保存到文本文件,

// The Save Path is the text file's Path, used to read and save
// Encode can use Encoding.Default
public static async void SaveTextFile(string StrToSave, string SavePath, Encoding ENCODE)
{
    // Part1  
    try
    {
        using (StreamReader sr = new StreamReader(SavePath, ENCODE))
        {
            string result = "";
            while (sr.EndOfStream != true)
                result = result + sr.ReadLine() + "\n";

            MessageBox.Show(result);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }

    // Part2
    try
    {
        using (FileStream fs = new FileStream(SavePath, FileMode.Create))
        {
            using (StreamWriter sw = new StreamWriter(fs, ENCODE))
            {
                await sw.WriteAsync(StrToSave);
                await sw.FlushAsync();
                sw.Close();
            }
            MessageBox.Show("Save");
            fs.Close();
        }
    }

    // The Run End Here And didn't Continue to Part 3

    catch (Exception e)
    {
        Console.WriteLine(e);
    }

    // Part3
    try
    {
        using (StreamReader sr = new StreamReader(SavePath, ENCODE))
        {
            string result = "";
            while (sr.EndOfStream != true)
                result = result + sr.ReadLine() + "\n";

            MessageBox.Show(result);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
}

但是我觉得很奇怪,在part2完成的地方流程就结束了,part3就直接结束了,没有继续,

出现这种情况的原因是什么?一般来说这个过程应该走完整个方法但不应该在中间停止

(多一题) 有没有其他方法可以达到part2的目的,也可以继续part3来完成整个方法?

这可能是因为您正在编写一个异步无效方法,并且您正在调用第 2 部分中的一些异步方法。尝试将第 2 部分中的异步方法更改为 non-async 方法:

using (StreamWriter sw = new StreamWriter(fs, ENCODE))
{
    sw.Write(StrToSave);
    sw.Flush(); // Non-async
    sw.Close(); // Non-async
}

它现在的行为是否符合您的预期?

问题是您告诉您的应用 await 方法,但从未获得任务结果或给它完成的机会。从你到目前为止所展示的内容来看,你根本不需要异步的东西,大大简化了代码:

public static void SaveTextFile(string StrToSave, string SavePath, Encoding ENCODE)
{
    //Part1  
    try
    {
        MessageBox.Show(File.ReadAllText(SavePath, ENCODE));
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }

    //Part2
    try
    {
        File.WriteAllText(SavePath, StrToSave, ENCODE);
        MessageBox.Show("Save");
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }

    //Part3
    try
    {
        MessageBox.Show(File.ReadAllText(SavePath, ENCODE));
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
}