Static Methods are thread safe, methods on primitives generally need to be thread safe to support threading in the platform (meaning at least safe from internal race conditions), instance methods take a managed pointer to a structure, meaning that the structure/primitive might be modified concurrently while the method executes, on the other hand static methods take a copy of the structure/primitive and therefore are safe from threading race conditions.
If the structure is intended to be thread safe, then the methods should be made instance methods only if they do atomic operations, else static methods should be chosen.
(As another option, instance methods that use locking could be used but they are more expensive than, copying)
Edit: @VirtualBlackFox I've prepared and example to show that instance methods on structures are not thread safe even on immutable structures:
using System;
using System.Threading;
namespace CA64213434234
{
class Program
{
static void Main(string[] args)
{
ManualResetEvent ev = new ManualResetEvent(false);
Foo bar = new Foo(0);
Action a = () => bar.Display(ev);
IAsyncResult ar = a.BeginInvoke(null, null);
ev.WaitOne();
bar = new Foo(5);
ar.AsyncWaitHandle.WaitOne();
}
}
public struct Foo
{
private readonly int val;
public Foo(int value)
{
val = value;
}
public void Display(ManualResetEvent ev)
{
Console.WriteLine(val);
ev.Set();
Thread.Sleep(2000);
Console.WriteLine(val);
}
}
}
The display Instance method prints:
0
5
even though the structure is immutable. For thread safe methods use static methods.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…