Saving the same file at the same time on different threads

4

In my software I have a thread that every second updates the file X. This same file can also be updated through a user action that will be in another thread (can be any time).

My question is: what will happen if both threads tries to save the X file at the exact same time? Is there a way to ensure that the file is updated in both cases?

I need to ensure that the file is updated in both cases. Failing to update the file is not an option.

I know it can be very rare to happen (in the exact thousandth of a second) two threads try to save the same file at the same time. But what if it does?

I'm currently using the code below to save the files:

using (var streamWriter = new StreamWriter(filename, false))
{
    streamWriter.WriteLine(encrypted);
}
    
asked by anonymous 04.05.2018 / 15:52

2 answers

4

The feature you want to access / manipulate (the file) is unique. So it's interesting that you centralize operations on a singleton object that is thread safe . Such a model forces the creation of a FIFO queue to access the resource.

Note that threads waiting for access will enter wait-state - however this is a small price to pay to guard atomicity of operations.

For an example of thread-safe singleton , read this article: Implementing the Singleton Pattern in C # (specifically the topics 'Second version - simple thread-safety' and 'Fifth version - fully lazy instantiation').

The following codes are copies of the article content (to avoid any broken links):

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

Version via static boot:

public sealed class Singleton
{
    private Singleton()
    {
    }

    public static Singleton Instance { get { return Nested.instance; } }

    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}
    
04.05.2018 / 17:44
3

It's not a direct answer that does what you want directly, but it's the answer you should follow.

Treating competition is difficult, doing it wrong is very easy, so it's better to use another mechanism that already does this. I recommend using SQLite .

That is, the two answers here are telling you to do something else :) Which one will be most appropriate for your case depends on the need that was not properly posted.

    
04.05.2018 / 17:52