SynchronizationContext.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. namespace System.Threading
  5. {
  6. public partial class SynchronizationContext
  7. {
  8. private bool _requireWaitNotification;
  9. public SynchronizationContext()
  10. {
  11. }
  12. #if !FEATURE_APPX && !ENABLE_WINRT
  13. public static SynchronizationContext? Current => Thread.CurrentThread._synchronizationContext;
  14. #endif
  15. protected void SetWaitNotificationRequired() => _requireWaitNotification = true;
  16. public bool IsWaitNotificationRequired() => _requireWaitNotification;
  17. public virtual void Send(SendOrPostCallback d, object? state) => d(state);
  18. public virtual void Post(SendOrPostCallback d, object? state) => ThreadPool.QueueUserWorkItem(s => s.d(s.state), (d, state), preferLocal: false);
  19. /// <summary>
  20. /// Optional override for subclasses, for responding to notification that operation is starting.
  21. /// </summary>
  22. public virtual void OperationStarted()
  23. {
  24. }
  25. /// <summary>
  26. /// Optional override for subclasses, for responding to notification that operation has completed.
  27. /// </summary>
  28. public virtual void OperationCompleted()
  29. {
  30. }
  31. [CLSCompliant(false)]
  32. public virtual int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)
  33. {
  34. return WaitHelper(waitHandles, waitAll, millisecondsTimeout);
  35. }
  36. [CLSCompliant(false)]
  37. protected static int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)
  38. {
  39. if (waitHandles == null)
  40. {
  41. throw new ArgumentNullException(nameof(waitHandles));
  42. }
  43. return WaitHandle.WaitMultipleIgnoringSyncContext(waitHandles, waitAll, millisecondsTimeout);
  44. }
  45. public static void SetSynchronizationContext(SynchronizationContext? syncContext) => Thread.CurrentThread._synchronizationContext = syncContext;
  46. public virtual SynchronizationContext CreateCopy() => new SynchronizationContext();
  47. }
  48. }