File writing in multithreaded system in C #

0

I'm developing a system in which I find myself in the following scenario: a program needs to create a file part by piece. It receives bytes from a server and so the file is created, it should work that way because it is a design decision.

The problem is that more than one thread may end up writing those bytes, so I think this would lead to a race condition. The way I dealt with this problem was the implementation of this class:

internal class ConcurrentFile
{
    private readonly object _padlock = new object();
    public string Path { get; set; }

    public ConcurrentFile(string path)
    {
        Path = path;
    }

    public void CreateEmpty()
    {
        lock (_padlock)
        {
            File.Create(Path).Dispose();
        }
    }

    public void Write(byte[] data)
    {
        lock (_padlock)
        {
            using(var fileStream = new FileStream(Path, FileMode.Append, FileAccess.Write, FileShare.Write))
            {
                fileStream.Write(data, 0, data.Length);
                fileStream.Flush();
            }
        }
    }
}

Is this a troublesome solution? What problems can I have? By the way, is this code really secure? Help me find a good solution! Thank you for your attention.

    
asked by anonymous 11.07.2018 / 05:23

0 answers