Search code examples
c#multithreadingasynchronousstreamwriter

The result written to the file does not work as expected


I use multithread to write the result to file. I have 100 results but the number of results saved to the file is only 30 results. What should I do?

    public async Task FileWriteAsync(string text)
    {
        string file = @"uid.txt";
        using (FileStream sourceStream = new FileStream(file, FileMode.Append, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
        using (StreamWriter f = new StreamWriter(sourceStream))
        {
            await f.WriteLineAsync(text);
        }
    }
    public void ExFile(int line)
    {

        var uid = Regex.Match(txt_ListUID.Lines[line], @"c_user=(.*?);").Groups[1].ToString().Trim();
        string text = uid + "|zxzxzx";
        _ = FileWriteAsync(text)
    }

Solution

  • You can try ReaderWriterLock Namespace: System.Threading

    .NET Framework provides several threading locking primitives. The ReaderWriterLock is one of them.

    The ReaderWriterLock class is used to synchronize access to a resource. At any given time, it allows concurrent read access to multiple (essentially unlimited) threads, or it allows write access for a single thread. In situations where a resource is read frequently but updated infrequently, a ReaderWriterLock will provide much better throughput than the exclusive Monitor lock.

    ReaderWriterLock Class examples

    Edited

    
       public async Task FileWriteAsync(string text)
        {
          ReaderWriterLock locker = new ReaderWriterLock();
         try
           {
             locker.AcquireWriterLock(int.MaxValue); //You might wanna change timeout value 
             string file = @"uid.txt";
             using (FileStream sourceStream = new FileStream(file, FileMode.Append, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
             using (StreamWriter f = new StreamWriter(sourceStream))
             {
                await f.WriteLineAsync(text);
             }
            }
            finally
            {
                locker.ReleaseWriterLock();
            }
        }
        public void ExFile(int line)
        {
    
            var uid = Regex.Match(txt_ListUID.Lines[line], @"c_user=(.*?);").Groups[1].ToString().Trim();
            string text = uid + "|zxzxzx";
            _ = FileWriteAsync(text)
        }