I have an issue which I think might be a Thread-Safety related issue. I've created a "simplified" version of my code to try and see if I can pick up any Thread Safety issues.
No matter how often I run this, I do not get a Thread-Safety issue. Can I assume that this "test" code is Thread-Safe?
class Program
{
static void Main()
{
Random random = new Random();
for (int i = 0; i < 10; i++)
{
new Thread(new AsmxService().Go).Start(random.Next(1, 10));
}
Console.Read();
}
}
public class AsmxService
{
public void Go(object obj)
{
StaticImport.Import((int)obj);
}
}
public class StaticImport
{
public static List<Lookup> lookups = new List<Lookup>()
{
new Lookup(1, "No. 1"),
new Lookup(2, "No. 2"),
new Lookup(3, "No. 3"),
new Lookup(4, "No. 4"),
new Lookup(5, "No. 5"),
new Lookup(6, "No. 6"),
new Lookup(7, "No. 7"),
new Lookup(8, "No. 8"),
new Lookup(9, "No. 9"),
new Lookup(10, "No. 10")
};
public static void Import(int id)
{
Lookup lu = lookups.First(l => l.Id == id);
Console.WriteLine("Go lookup, Id: {0} & Name: {1}", lu.Id, lu.Name);
// Import here
if (lu.Id != id)
{
throw new Exception(string.Format("Thread Safety issue! Id passed in: {0}, Id on instance: {1}***", id, lu.Id));
}
else
{
Console.WriteLine("Successful!");
}
}
}
public class Lookup
{
public Lookup(int id, string name)
{
this.Id = id;
this.Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
}
Just to make sure my test code correctly represents my actual code, here is the logical flow:
- An external system (represented by the Console App)
- sends multiple calls simultaneously (represented by mulitple threads)
- to the an ASMX service (represented by 'AsmxService' class)
- which calls a static class (represented by 'StaticImport')
- which does a lookup to SQL (represented by List lookups field)
- Some validation (represented by Console.WriteLine)
- then after some validation, the lookup instance used to import some stuff into the database
My question is, at this last step (7.), is it possible that looked up value (step 5.) has changed because of thread safety issues?
Thank you in advance.