PageRenderTime 38ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/Branches/0.9.5-DeltaShell/src/Common/DelftTools.Utils/Threading/ThreadsafeBindingList.cs

#
C# | 62 lines | 41 code | 8 blank | 13 comment | 4 complexity | c457ecb6464424f435a52c08fc6f5b1f MD5 | raw file
Possible License(s): LGPL-2.1
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Threading;
  5. namespace DelftTools.Utils.Threading
  6. {
  7. /// <summary>
  8. /// Provides a thread-safe binding-list by using the synchronizationcontext where the list was created.
  9. /// HACK: Probably not full-proof.
  10. /// Copied from: http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/msg/f12a3c5980567f06
  11. /// List should be created in a forms control providing a synchronization context
  12. /// More about synchronizationcontext here: http://www.codeproject.com/KB/cpp/SyncContextTutorial.aspx
  13. /// </summary>
  14. /// <typeparam name="T"></typeparam>
  15. public class ThreadsafeBindingList<T> : BindingList<T>
  16. {
  17. private readonly SynchronizationContext synchronizationContext;
  18. protected override void OnAddingNew(AddingNewEventArgs e)
  19. {
  20. synchronizationContext.Send(delegate { BaseAddingNew(e); }, null);
  21. }
  22. void BaseAddingNew(AddingNewEventArgs e)
  23. {
  24. base.OnAddingNew(e);
  25. }
  26. protected override void OnListChanged(ListChangedEventArgs e)
  27. {
  28. synchronizationContext.Send(
  29. delegate { BaseListChanged(e); }, null);
  30. }
  31. void BaseListChanged(ListChangedEventArgs e)
  32. {
  33. base.OnListChanged(e);
  34. }
  35. /// <summary>
  36. /// Creates a bindinglist using the givin synchronization context
  37. /// </summary>
  38. public ThreadsafeBindingList(SynchronizationContext context)
  39. {
  40. synchronizationContext = context;
  41. //for now this class can only be used in synchronization context
  42. if (synchronizationContext == null)
  43. throw new InvalidOperationException("Unable to create a threadsafe bindinglist without a synchronization context");
  44. }
  45. public ThreadsafeBindingList(SynchronizationContext context, IList<T> list)
  46. : base(list)
  47. {
  48. synchronizationContext = context;
  49. //for now this class can only be used in synchronization contexts
  50. if (synchronizationContext == null)
  51. throw new InvalidOperationException("Unable to create a threadsafe bindinglist without a synchronization context");
  52. }
  53. }
  54. }