I have a data synchronisation operation that is observing a database. This is a fairly key piece of code for the system, so I want to make sure I handle the concurrency correctly.The problemThe operation manipulates sync state flags in the database and shouldhave zero concurrency The operation must be cancellableThe operation should repeat an additional time if signals are received while it is runningBehaviorThe service is started in response to changes to the underlying dataThe service is started in response to changes in connectivity The service is started periodicallyCurrent design    bool syncRequired = false;    private async void StartSynchronisation()    {        // the cancellation token operates as the flag to indicate if the operation is running        if (this.cancellationTokenSource != null)        {            syncRequired = true;            return;        }        try        {            this.cancellationTokenSource = new System.Threading.CancellationTokenSource();            // stop the time that periodically prompt the operation            this.synchronisationTimer.Stop();            bool dataWasSynchronised = false;            // Repeated synchronisation and replication until no updates are made            do            {                syncRequired = false;                // Only attempt synchronisation if the service is actually available                if (this.connectivityMonitor.IsServiceAvailable)                {                    dataWasSynchronised = await DoSynchronisation().ConfiguredAwait(false);                }            }            while (dataWasSynchronised || syncRequired );        }        catch (Exception ex)        {            // handle exception using injected policy handler        }        finally        {            this.synchronisationTimer.Start();            this.cancellationTokenSource.Dispose();            this.cancellationTokenSource = null;        }    }I bring you this code because it is missing any thread synchronisation and it probably needs it. It currently relies on the atomicity of read/writes to a reference (cancellationTokenSource) and bool (syncRequired) but this doesn't cover anything really. As a critical piece of code, I don't want to miss an event and need to wait for the next timer interval to start the operation. It will continue working, but our test department won't like it. My issue is, thread concurrency isn't my strongest area and I'm already burned out on this feature - I'm struggling to reason about it without tying my head in knots.What synchronisation primitives do I need to make sure all events are handled as intended? Is there a more favourable pattern using concurrent queues or reactive extensions that I can throw in here? I have been considering some use of Reactive Extension's BehaviorSubject<T>.
Repeat operation if signal is received
c#;concurrency;locking