Search code examples
c#parallel.foreach

Reading static variable in Parallel.Foreach


Is it safe to read from the static variable inside of Parallel.ForEach

class Program
{
    private static string _startTime;

    static void Main(string[] args)
    {
        _startTime = DateTime.Now.ToString();
        Parallel.ForEach(args,
        arg =>
        {
            Process(arg);
        });
    }

    private static void Process(string arg)
    {
        //Can I read _processStartTime variable here
        var startDateTime = _startTime;
        
    }
}

This article mentions about reading from a static variable but did not provide more information.

https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/potential-pitfalls-in-data-and-task-parallelism


Solution

  • Reading is fine (so long as all threads are just reading).

    Editing requires thread-safety. If any thread will edit the data, even if the others are just reading, thread-safety needs to be addressed.

    If the thing you were reading got it's data from computation or an external source, you'd need to think about thread-safety too, but in this particular example it's perfectly safe because it will always be the same value every time.

    If you had a more real life example, you'll need to be aware of potential pitfalls, but for simple reads, it's not an issue.