code_junkie

Is a string property itself threadsafe?

Nov 13th, 2011
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. public String SampleProperty{
  2. get;
  3. private set;
  4. }
  5.  
  6. private string sampleField;
  7. private object threadSafer = new object();
  8.  
  9. public String SampleProperty{
  10. get{ return this.sampleField; }
  11. private set{
  12. lock(threadSafer){
  13. sampleField = value;
  14. }
  15. }
  16. }
  17.  
  18. class BackgroundTaskDemo
  19. {
  20. private bool stopping = false;
  21.  
  22. static void Main()
  23. {
  24. BackgroundTaskDemo demo = new BackgroundTaskDemo();
  25. new Thread(demo.DoWork).Start();
  26. Thread.Sleep(5000);
  27. demo.stopping = true;
  28. }
  29.  
  30. static void DoWork()
  31. {
  32. while (!stopping)
  33. {
  34. // Do something here
  35. }
  36. }
  37. }
  38.  
  39. lock(someExternalLock) {
  40. record.Foo = "Bar";
  41. }
  42.  
  43. lock(record.SyncLock) {
  44. record.Foo = "Bar";
  45. }
  46.  
  47. obj.SampleProperty = "Dear " + firstName + " " + lastName;
  48.  
  49. obj.SampleProperty += obj.SampleProperty + "a";
  50.  
  51. obj.SampleProperty = "Initial String Value";
Add Comment
Please, Sign In to add comment