I did a simple testing of extension method with a class (reference type), the result looks good (thread safe).
Main Program
static void Main(string[] args)
{
List<Car> cars = new List<Car>();
cars.Add(new Car() { Brand = "Alfa Romeo", PlateNo = "A1" });
cars.Add(new Car() { Brand = "BMW", PlateNo = "B1" });
cars.Add(new Car() { Brand = "Honda", PlateNo = "H1" });
cars.Add(new Car() { Brand = "Mercedes", PlateNo = "M1" });
cars.Add(new Car() { Brand = "Renault", PlateNo = "R1" });
cars.Add(new Car() { Brand = "Toyota", PlateNo = "T1" });
Parallel.ForEach(cars, car =>
{
new ParallelOptions { MaxDegreeOfParallelism = 2 };
Console.WriteLine($"Step 1, thread id {Thread.CurrentThread.ManagedThreadId}: {car.Brand} - {car.PlateNo}");
car.ChangePlateNo();
Console.WriteLine($"Step 4, thread id {Thread.CurrentThread.ManagedThreadId}: {car.Brand} - {car.PlateNo}");
});
Console.WriteLine("Press any key to close.");
}
Car Class
public class Car
{
public string Brand { get; set; }
public string PlateNo { get; set; }
}
Extension method
public static class Extension
{
public static void ChangePlateNo(this Car car)
{
Console.WriteLine($"Step 2, thread id {Thread.CurrentThread.ManagedThreadId}: {car.Brand} - {car.PlateNo}");
// let a record sleep 3 seconds
if (car.Brand == "BMW")
System.Threading.Thread.Sleep(3000);
car.PlateNo = car.PlateNo + "2";
Console.WriteLine($"Step 3, thread id {Thread.CurrentThread.ManagedThreadId}: {car.Brand} - {car.PlateNo}");
}
}
Output
Step 1, thread id 1: Alfa Romeo - A1
Step 1, thread id 4: Honda - H1
Step 1, thread id 3: BMW - B1
Step 1, thread id 5: Mercedes - M1
Step 1, thread id 7: Toyota - T1
Step 1, thread id 6: Renault - R1
Step 2, thread id 6: Renault - R1
Step 3, thread id 6: Renault - R12
Step 4, thread id 6: Renault - R12
Step 2, thread id 1: Alfa Romeo - A1
Step 3, thread id 1: Alfa Romeo - A12
Step 4, thread id 1: Alfa Romeo - A12
Step 2, thread id 4: Honda - H1
Step 3, thread id 4: Honda - H12
Step 4, thread id 4: Honda - H12
Step 2, thread id 7: Toyota - T1
Step 3, thread id 7: Toyota - T12
Step 4, thread id 7: Toyota - T12
Step 2, thread id 3: BMW - B1
Step 2, thread id 5: Mercedes - M1
Step 3, thread id 5: Mercedes - M12
Step 4, thread id 5: Mercedes - M12
Step 3, thread id 3: BMW - B12
Step 4, thread id 3: BMW - B12