Skip to content

Document thread-safety of read-only access for mutable collections #8658

Open
@ohads-MSFT

Description

@ohads-MSFT

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

Options use caching, for example:
https://github.com/dotnet/runtime/blob/e2c0735927642a11162c0d12799be2921bd1c984/src/libraries/Microsoft.Extensions.Options/src/UnnamedOptionsManager.cs#L25

Since TOptions<TOptions> are registered at the singleton scope, any two DI participants (e.g. controller instances) may receive the same TOptions instance when they retrieve it using IOptions<T>.Value.

This means that any user of the Options class must assume concurrent access to the classes' members. Now, for most boundable types (like string or int) this won't be an issue. However, for collection types, this potentially becomes more complicated. Even if the first thing I do is store a IOptions<T>.Value.ToImmutableArray() , this still incurs enumeration. It is not clear to me that all boundable collection types are thread safe even for read-only enumeration of the original collection in the shared TOptions class. And while I suspect arrays possess this property, I do not see any such mention for e.g. HashSet<T>.

Expected Behavior

Guarantee at the ASP.NET level that all boundable Options collection types are thread safe for concurrent enumeration. For example, if HashSet<T> does not provide this guarantee, you could create a subclass of it that does provide it, and inject it into bound TOptions classes.

Steps To Reproduce

public class MyOptions { HashSet<string> MySet {get; set;} }

public class MyController
{
   public MyController(IOptions<MyOptions> options)
   {
      foreach (string s in options.Value.MySet) { Console.WriteLine(s);  }
   }
}

Exceptions (if any)

In theory, things like NullReferenceException or similar unexpected exceptions when non thread safe operations are performed.

.NET Version

6.0.403

Anything else?

In case I'm wrong and all boundable collections are thread safe for readonly enumeration, I believe it should be specified clearly in all the relevant documentation pages. I guess in that case that would be more of a dotnet docs bug, but considering the aforementioned singleton registration of IOptions<T> I think it's something you should address in your docs too.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions