C# 异步写文件

如果在 多线程的环境下, File.AppentText 就不适应了。 

FileStream 具备读写异步文件的能力。 

 

private static Dictionary<long, long> lockDic = new Dictionary<long, long>();     
public static void Save(string txt,string path)
        {

            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }
            if (string.IsNullOrEmpty(txt))
                return;

            var bytes = Encoding.UTF8.GetBytes(txt);

            using (var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, 8, FileOptions.Asynchronous))
            {
                bool flag = true;
                long slen = bytes.Length;
                long len = 0;
                while (flag)
                {
                    try
                    {
                        if (len >= fs.Length)
                        {
                            fs.Lock(len, slen);
                            lockDic[len] = slen;
                            flag = false;
                        }
                        else
                        {
                            len = fs.Length;
                        }
                    }
                    catch (Exception)
                    {
                        while (!lockDic.ContainsKey(len))
                        {
                            len += lockDic[len];
                        }
                    }
                }
                fs.Seek(len, System.IO.SeekOrigin.Begin);
                fs.Write(bytes, 0, bytes.Length);
                fs.Close();
            }
        }