jeudi 18 août 2022

Prevent the reference to any mutable state in a delegate

For a little framework that will be used in C# 10 (or newer) projects I would like to build a processor that is optimized for executing CPU bound (CPU intensive) user code asynchronously and concurrently. The goal of this processor is that it makes it very hard (or even impossible) to access mutable state inside that user code, therefore helping the novice developer not shooting themselves in the foot by running into concurrency issues.

For that I have created a delegate like so:

// InputData and OutputData are guaranteed to be fully immutable
public delegate Task<OutputData> ProcessDelegate(InputData input, CancellationToken cancellationToken);

The processor has a method that can take an instance of the delegate:

public class Processor
{
    public Task<OutputData> ProcessAsync(
        ProcessDelegate process, InputData input, CancellationToken cancellationToken)
    {
        // the process delegate is queued and executed based on different strategies
    }
}

Now my question:

How can I make it hard (or even impossible?) for the novice user to use any reference to an object that contains mutable state inside the user code (body) of the delegate that is passed to the ProcessAsync method of the Processor class?

Maybe I could ship the framework with an analyzer that detects this and puts out a warning?

If detecting mutable state is too hard to achieve, is there a way to detect whether the delegate body uses any reference except the InputData and CancellationToken passed to it?

Please keep in mind that ProcessAsync can be called in many ways (lamda, local function, instance method, static method, anonymous delegate etc.)





Aucun commentaire:

Enregistrer un commentaire