Skip to content

Instantly share code, notes, and snippets.

@itn3000
Last active September 21, 2022 11:37
Show Gist options
  • Save itn3000/bf26a0ae8f0f4b6037392996d0ea1349 to your computer and use it in GitHub Desktop.
Save itn3000/bf26a0ae8f0f4b6037392996d0ea1349 to your computer and use it in GitHub Desktop.
MessagePipe Unix domain socket example
// you can run this code in Linux,macOS,Windows(10 April 2018 or later)
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Threading;
using System.Threading.Tasks;
using System;
using MessagePipe;
public class RemotePublisher : BackgroundService
{
IDistributedPublisher<int, int> _Publisher;
public RemotePublisher(IDistributedPublisher<int, int> pub)
{
_Publisher = pub;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await Task.Yield();
for (int i = 0; i < 10 && !stoppingToken.IsCancellationRequested; i++)
{
await _Publisher.PublishAsync((i % 2) + 1, i);
try { await Task.Delay(1000, stoppingToken).ConfigureAwait(false); } catch { }
}
Console.WriteLine("remote pub end");
}
}
public class RemoteSubscriber : BackgroundService
{
IDistributedSubscriber<int, int> _Subscriber;
public RemoteSubscriber(IDistributedSubscriber<int, int> sub)
{
_Subscriber = sub;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await using (await _Subscriber.SubscribeAsync(1, x => System.Console.WriteLine($"remote sub: 1, {x}")))
await using (await _Subscriber.SubscribeAsync(2, x => System.Console.WriteLine($"remote sub: 2, {x}")))
await using (await _Subscriber.SubscribeAsync(2, x => System.Console.WriteLine($"remote sub: 3, {x}")))
{
try
{
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(1000, stoppingToken);
}
}
catch { }
}
}
}
static partial class PipeTest
{
public static async Task RemoteTest()
{
using var cts = new CancellationTokenSource();
await Host.CreateDefaultBuilder()
.ConfigureServices(builder =>
{
builder.AddMessagePipe()
.AddMessagePipeTcpInterprocessUds("hoge.sock")
.AddHostedService<RemoteSubscriber>()
.AddHostedService<RemotePublisher>();
})
.RunConsoleAsync(cts.Token)
;
}
}
@sgf
Copy link

sgf commented Sep 21, 2022

im confused,AddMessagePipeTcpInterprocessUds looks not coress process.
how does it interprocess ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment