Created
January 21, 2023 06:23
-
-
Save IzStriker/afcdac0e9d85d4fdd94477ae8eb8f136 to your computer and use it in GitHub Desktop.
C# Message Queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma warning disable CS8618 | |
public class Message<T> where T : class | |
{ | |
public T Payload { get; set; } | |
public string Channel { get; set; } | |
} | |
#pragma warning restore CS8618 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Concurrent; | |
using System.Reflection; | |
public class MessageQueue | |
{ | |
private readonly BlockingCollection<object> _queue; | |
public MessageQueue() | |
{ | |
_queue = new BlockingCollection<object>(); | |
} | |
public void Subscribe<T>(string channel, Func<T, Task> action) where T : class | |
{ | |
Task.Run(() => | |
{ | |
foreach (var message in _queue.GetConsumingEnumerable()) | |
{ | |
if (message is Message<T> && ((Message<T>)message).Channel == channel) | |
{ | |
action(((Message<T>)message).Payload); | |
} | |
} | |
}); | |
} | |
public void Send<T>(string channel, T message) where T : class | |
{ | |
_queue.Add(new Message<T> | |
{ | |
Channel = channel, | |
Payload = message | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment