这种场景的无锁设计是否合理

Is it a reasonable approach for lock-free design for this scenario

这是对我之前的一个问题 的跟进。总之,我正在尝试为这种情况提出一种无锁设计,在取消任务后我想调用第三方库的方法。在回答我的问题时,一位乐于助人的 SO 参与者建议使用 CancellationToken.Register 但我不确定在这里可以在哪里以及如何使用它。下面是我想出的代码。如果您发现此方法有任何问题,或者是否有更好的替代方法来解决此问题,请告诉我。

class ProcessEmployees
    {
        private List<Employee> _Employees;
        CancellationTokenSource cs = new CancellationTokenSource();

        public  ProcessEmployees()
        {
            _Employees = new List<Employee>() 
            {
                new Employee() { ID = 1, FirstName = "John", LastName = "Doe" },
                new Employee() { ID = 2, FirstName = "Peter", LastName = "Saul" },
                new Employee() { ID = 3, FirstName = "Mike", LastName = "Sue" },
                new Employee() { ID = 4, FirstName = "Catherina", LastName = "Desoza" },
                new Employee() { ID = 5, FirstName = "Paul", LastName = "Smith" }
            };
        }

        public void StartProcessing()
        {
            try
            {
                Task[] tasks = this._Employees.AsParallel().WithCancellation(cs.Token).Select(x => this.ProcessThisEmployee(x, cs.Token)).ToArray();
                Task.WaitAll(tasks);
            }
            catch (AggregateException ae)
            {
                // error handling code
            }
            // other stuff
        }

        private async Task ProcessThisEmployee(Employee x, CancellationToken token)
        {
            ThirdPartyLibrary library = new ThirdPartyLibrary();
            if (token.IsCancellationRequested)
                token.ThrowIfCancellationRequested();
            await Task.Factory.StartNew(() => library.SomeAPI(x) );
            if (token.IsCancellationRequested)
            {
                library.Clean();
                token.ThrowIfCancellationRequested();
            }
        }
    }

你的流程代码可以简化为如下(这里是你使用Register的方法)

private void ProcessThisEmployee(Employee x, CancellationToken token)
{
    ThirdPartyLibrary library = new ThirdPartyLibrary();
    token.ThrowIfCancellationRequested();
    using(token.Register(() => library.Clean())
    {
        library.SomeAPI(x);
    }
    token.ThrowIfCancellationRequested(); //Not sure why you cancel here in your original example.
}

如果令牌在 using 语句范围内被取消,它将调用 library.Clean() 如果之后调用它,则它不会调用该函数。我也摆脱了你的 Task.Run,没有理由为你正在做的事情浪费额外的线程。最后,我摆脱了额外的 if (token.IsCancellationRequested) 检查,ThrowIfCancellationRequested() 有如果检查自身内部,你不需要事先检查。

此外,因为在我的简化中您不再返回任务,所以您的 StartProcessing 代码变为

    public void StartProcessing()
    {
        try
        {
            this._Employees.AsParallel().WithCancellation(cs.Token).ForAll(x => this.ProcessThisEmployee(x, cs.Token));
        }
        catch (AggregateException ae)
        {
            // error handling code
        }
        // other stuff
    }

使用 ForAll( 而不是 Select(