Driver - Write async driver inputs sync

PHOTO EMBED

Wed Jan 19 2022 12:14:50 GMT+0000 (UTC)

Saved by @xxxdomi #c#

// Datapoint implements ...
internal interface ISynchronousWrite
{
    DateTime LastWrite { get; set; }

    object BufferedValue { get; set; }

    WriteResult LastWriteResult { get; set; }

    void WriteBufferedValueToDevice();
}

// Item broker starts thread and creates...
private CancellationTokenSource cancellationTokenSource;
private CancellationToken ct;
private bool exitWriteTask = false;   
private ConcurrentDictionary<IDatapointItem, DateTime> inputDatapointBuffer = new ConcurrentDictionary<IDatapointItem, DateTime>();


foreach (var dpItem in DatapointItems.Values)
{
    if (dpItem.InitDatapoint.Task == DatapointTaskEnum.SetValues)
    {
        inputDatapointBuffer.TryAdd(dpItem, DateTime.Now);
    }
}

cancellationTokenSource = new CancellationTokenSource();
ct = cancellationTokenSource.Token;

var intervalWritingTask = Task.Run(() =>
{
    while (!exitWriteTask)
    {
        if (Connection.IsConnected)
        {
            foreach (var key in inputDatapointBuffer.Keys)
            {
                var dp = key as ISynchronousWrite;
                var lastTempWriteTime = dp.LastWrite;
                if (inputDatapointBuffer[key] < lastTempWriteTime)
                {
                    dp.WriteBufferedValueToDevice();
                    inputDatapointBuffer[key] = lastTempWriteTime;
                }
            }
        }

        Thread.Sleep(10);
    }
}, ct);

// Implementation
private WriteResult BufferValue(object value)
{
    BufferedValue = value;
    LastWrite = DateTime.Now;
    return LastWriteResult;
}
content_copyCOPY