/// <summary> /// Body of critical section for non-async environment. /// <para> /// The worker periodically sets the shared value to its ID and waits. /// If another thread enters the critical section, the shared value will be modified /// and the worker reports an error. /// </para> /// </summary> /// <param name="workerContext">Shared information the worker needs for the task.</param> /// <remarks>The caller is responsible for holding <see cref="WorkerContext.Lock"/>.</remarks> private void CriticalSectionLocked(WorkerContext workerContext) { int id = workerContext.GetWorkerId(); for (int i = 0; i < 5; i++) { workerContext.SharedValue = id; int delay = workerContext.Rng.Next(200); Thread.Sleep(delay); // If other thread enters the critical section, the error will be set. workerContext.Error |= workerContext.SharedValue != id; } }
/// <summary> /// Body of critical section for async environment. /// <para> /// The worker periodically sets the shared value to its ID and waits. /// If another thread enters the critical section, the shared value will be modified /// and the worker reports an error. /// </para> /// </summary> /// <param name="workerContext">Shared information the worker needs for the task.</param> /// <remarks>The caller is responsible for holding <see cref="WorkerContext.Lock"/>.</remarks> private async Task CriticalSectionLockedAsync(WorkerContext workerContext) { int id = workerContext.GetWorkerId(); for (int i = 0; i < 5; i++) { workerContext.SharedValue = id; int delay = workerContext.Rng.Next(200); await Task.Delay(delay); // If other thread enters the critical section, the error will be set. workerContext.Error |= workerContext.SharedValue != id; } }