|
| 1 | +Async Await |
| 2 | +=========== |
| 3 | + |
| 4 | +Since version (4.0.0.239-pre) NetMQ support async/await. |
| 5 | + |
| 6 | +To use async/await feature you need to create a `NetMQRuntime`. |
| 7 | + |
| 8 | +## Example: |
| 9 | + |
| 10 | +```csharp |
| 11 | +async Task ServerAsync() |
| 12 | +{ |
| 13 | + using (var server = new RouterSocket("inproc://async")) |
| 14 | + { |
| 15 | + for (int i = 0; i < 1000; i++) |
| 16 | + { |
| 17 | + var (routingKey, more) = await server.ReceiveRoutingKeyAsync(); |
| 18 | + var (message, _) = await server.ReceiveFrameStringAsync(); |
| 19 | + |
| 20 | + // TODO: process message |
| 21 | +
|
| 22 | + await Task.Delay(100); |
| 23 | + server.SendMoreFrame(routingKey); |
| 24 | + server.SendFrame("Welcome"); |
| 25 | + } |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +async Task ClientAsync() |
| 30 | +{ |
| 31 | + using (var client = new DealerSocket("inproc://async")) |
| 32 | + { |
| 33 | + for (int i = 0; i < 1000; i++) |
| 34 | + { |
| 35 | + client.SendFrame("Hello"); |
| 36 | + var (message, more) = await client.ReceiveFrameStringAsync(); |
| 37 | + |
| 38 | + // TODO: process reply |
| 39 | +
|
| 40 | + await Task.Delay(100); |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +static void Main(string[] args) |
| 46 | +{ |
| 47 | + using (var runtime = new NetMQRuntime()) |
| 48 | + { |
| 49 | + runtime.Run(ServerAsync(), ClientAsync()); |
| 50 | + } |
| 51 | +} |
| 52 | +``` |
| 53 | + |
| 54 | +NetMQRuntime is a wrapper over NetMQPoller, when calling an async function the socket is automatically added to the internal poller. |
| 55 | +NetMQRuntime is also a NetMQScheduler and SyncrhonizationContext, so any awaited function is continuing on the runtime's thread. |
| 56 | + |
| 57 | +NetMQSocket should still be used only within one thread. |
| 58 | + |
| 59 | +`NetMQRuntime.Run` can accept multiple tasks and also a cancellation token. |
| 60 | +`NetMQRuntime.Run` runs until all tasks are completed or cancellation token has been cancelled. |
0 commit comments