ThreadSafeSocketExtensions.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System.Diagnostics;
  2. using System.Threading;
  3. namespace NetMQ
  4. {
  5. /// <summary>
  6. /// Thread-safe socket extension methods
  7. /// </summary>
  8. public static class ThreadSafeSocketExtensions
  9. {
  10. /// <summary>
  11. /// Block until the message can be sent.
  12. /// </summary>
  13. /// <remarks>
  14. /// The call blocks until the message can be sent and cannot be interrupted.
  15. /// Whether the message can be sent depends on the socket type.
  16. /// </remarks>
  17. /// <param name="socket">Socket to transmit on</param>
  18. /// <param name="msg">An object with message's data to send.</param>
  19. public static void Send(this IThreadSafeSocket socket, ref Msg msg)
  20. {
  21. var result = socket.TrySend(ref msg, SendReceiveConstants.InfiniteTimeout);
  22. Debug.Assert(result);
  23. }
  24. /// <summary>
  25. /// Block until the next message arrives, then make the message's data available via <paramref name="msg"/>.
  26. /// </summary>
  27. /// <remarks>
  28. /// The call blocks until the next message arrives, and cannot be interrupted. This a convenient and safe when
  29. /// you know a message is available, such as for code within a <see cref="NetMQSocket.ReceiveReady"/> callback.
  30. /// </remarks>
  31. /// <param name="socket">Socket to transmit on</param>
  32. /// <param name="msg">An object to receive the message's data into.</param>
  33. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
  34. /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception>
  35. public static void Receive(this IThreadSafeSocket socket, ref Msg msg, CancellationToken cancellationToken = default)
  36. {
  37. var result = socket.TryReceive(ref msg, SendReceiveConstants.InfiniteTimeout, cancellationToken);
  38. if (!result)
  39. cancellationToken.ThrowIfCancellationRequested();
  40. Debug.Assert(result);
  41. }
  42. }
  43. }