vendredi 13 novembre 2020

What's the best pattern for a thread safe write cache to database?

I've a Method which could be called by multiple Threads, to write data to a Database. To reduce Database traffic, I cache the Data and write it in a bulk.

Now I wanted to know, is there a better (for example lock-free pattern) to use?

public class WriteToDatabase : IWriter
{
    public WriteToDatabase()
    {
        writeTimer = new System.Threading.Timer(Writer);
        writeTimer.Change(500, 500);
    }

    private System.Threading.Timer writeTimer;
    private List<PlcProtocolDTO> writeChache = new List<PlcProtocolDTO>(); 


    public void Write(PlcProtocolDTO row)
    {
        lock (this)
        {
            writeChache.Add(row);
        }
    }

    private void Writer(object state)
    {
        List<PlcProtocolDTO> oldCachce;
        lock (this)
        {
            oldCachce = writeChache;
            writeChache = new List<PlcProtocolDTO>();
        }

        try
        {
            using (var s = VisuDL.CreateSession())
            {
                s.Insert(oldCachce);
            }
        }
        catch (Exception ex)
        {
            TraceSystem.Instance.Error("PLCProtocol", "TCP/IP Protokoller - WriteToDatabase.Write()", ex);
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire