"are .net ref parameters thread-safe, or vulnerable to unsafe multithreaded access?" Code Answer


when you use ref, you are passing the address of the caller's field/variable. therefore yes: two threads can compete over the field/variable - but only if they both are talking to that field/variable. if they have a different field/variable to the same instance, then things are sane (assuming it is immutable).

for example; in the code below, register does see the changes that mutate makes to the variable (each object instance is effectively immutable).

using system;
using system.threading;
class foo {
    public string bar { get; private set; }
    public foo(string bar) { bar = bar; }
static class program {
    static foo foo = new foo("abc");
    static void main() {
        new thread(() => {
            register(ref foo);
        for (int i = 0; i < 20; i++) {
            mutate(ref foo);
    static void mutate(ref foo obj) {
        obj = new foo(obj.bar + ".");
    static void register(ref foo obj) {
        while (obj.bar.length < 10) {
By murvinlai on August 20 2022

Answers related to “are .net ref parameters thread-safe, or vulnerable to unsafe multithreaded access?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.