code_junkie

Does the lock(objlocker) make that object thread safe app wide? And are static members automatically thread safe?

Nov 12th, 2011
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. static void AddItems( )
  2. {
  3. for (int i = 0; i < 100; i++)
  4. lock (list)
  5. list.Add ("Item " + list.Count);
  6.  
  7. string[] items;
  8. lock (list) items = list.ToArray( );
  9. foreach (string s in items) Console.WriteLine (s);
  10. }
  11.  
  12. lock (list)
  13. list.Add ("Item " + list.Count);
  14.  
  15. lock (list) items = list.ToArray( );
  16.  
  17. class UsefulStuff {
  18. object _TheLock = new object { };
  19. public void UsefulThingNumberOne() {
  20. lock(_TheLock) {
  21. //CodeBlockA
  22. }
  23. }
  24. public void UsefulThingNumberTwo() {
  25. lock(_TheLock) {
  26. //CodeBlockB
  27. }
  28. }
  29. }
  30.  
  31. public class Foo
  32. {
  33. private static Foo instance = new Foo();
  34.  
  35. public static Foo Instance
  36. {
  37. get { return instance; }
  38. }
  39. }
Add Comment
Please, Sign In to add comment