Skip to content

Throw a better exception when the HttpContext is accessed concurrently and will result in a null ref #42040

@davidfowl

Description

@davidfowl

We've had issues over the the years about random null refs that occur when accessing the HttpContext:

There are examples of concurrent access to the HttpContext. This usually happens because the internal feature references cache can be cleared after a new feature has been set. This happens on reading some properties (because it's lazily evaluated).

Instead, we should handle this case by throwing an exception saying that there was concurrent modification.

Here's a simple example that illustrates why there's a null ref:

var references = new Reference<ReferenceHolder>();

var myfeature = references.Fetch(ref references.Cache.NameFeature, () => new MyNameRequestFeature { Name = "New Feature" });

// This blows up with a null ref
var name = myfeature.Name;

Console.WriteLine(name);

struct Reference<T>
{
    public T? Cache;

    public R Fetch<R>(ref R? item, Func<R> factory)
    {
        item = factory();

        // Clear the cache
        Cache = default;

        return item;
    }
}

struct ReferenceHolder
{
    public MyNameRequestFeature? NameFeature;
}

class MyNameRequestFeature
{
    public string Name { get; init; } = default!;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-networkingIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions