Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8162153
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T18:38:49+00:00 2026-06-06T18:38:49+00:00

I’m implementing a simple chat in .NET using Rx on the basis of this

  • 0

I’m implementing a simple chat in .NET using Rx on the basis of this example:
https://blogs.claritycon.com/blog/2011/04/roll-your-own-mvc-3-long-polling-chat-site/

There’s a method that, using LongPolling waits for new messages to come:

public static void CheckForMessagesAsync(Action<List<MessageInfo>> onMessages)
{
    var queued = ThreadPool.QueueUserWorkItem(new WaitCallback(parm =>
    {
        var msgs = new List<MessageInfo>();
        var wait = new AutoResetEvent(false);
        using (var subscriber = _messages.Subscribe(msg =>
                                        {
                                            msgs.Add(msg);
                                            wait.Set();
                                        }))
        {
            // Wait for the max seconds for a new msg
            wait.WaitOne(TimeSpan.FromSeconds(MaxWaitSeconds));
        }

        ((Action<List<MessageInfo>>)parm)(msgs);
    }), onMessages);

    if (!queued)
        onMessages(new List<MessageInfo>());
}

Using this method I lose messages appearing between disconnecting and disposing the observer and re-connecting.
How to correctly implement this mechanism to not lose those messages?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T18:38:50+00:00Added an answer on June 6, 2026 at 6:38 pm

    I found a solution. I do not know whether it is the most beautiful in the world, but it works.
    I created private property, so each user can have multiple sessions:

    private ConcurrentDictionary<long, ChatServerUserSessions> _chatServerUserSessionInfoDictionary = new ConcurrentDictionary<long, ChatServerUserSessions>();
    

    and session class:

    public class ChatServerUserSessions
    {
        public long UserId { get; set; }
    
        public string UserName { get; set; }
    
        public ConcurrentDictionary<string, ChatServerUserSessionInfo> Sessions { get; set; }
    
        public object Lock { get; set; }
    }
    

    and for each session I created class:

    public class ChatServerUserSessionInfo : IObservable<ChatServerRoomActivityInfoBase>, IDisposable
    {
        public string SessionId { get; set; }
    
        public List<long> SubscribedRoomIds { get; set; }
    
        public DateTime SubscriptionTicketInvalidationDate { get; set; }
    
        public Queue<ChatServerRoomActivityInfoBase> MessagesQueue { get; set; }
    
        private IDisposable subscription;
        private List<IObserver<ChatServerRoomActivityInfoBase>> observers;
        private ChatServerUserSessions parentUserSessions;
    
        public ChatServerUserSessionInfo(string sessionId, DateTime subscriptionTicketInvalidationDate, Subject<ChatServerRoomActivityInfoBase> chatServerRoomActivity, ChatServerUserSessions parentUserSessions)
        {
            this.SessionId = sessionId;
            this.SubscribedRoomIds = new List<long>();
            this.SubscriptionTicketInvalidationDate = subscriptionTicketInvalidationDate;
            this.MessagesQueue = new Queue<ChatServerRoomActivityInfoBase>();
            this.parentUserSessions = parentUserSessions;
    
            subscription = chatServerRoomActivity.Subscribe(activity =>
            {
                lock (parentUserSessions.Lock)
                {
                    if (this.SubscribedRoomIds.Contains(activity.RoomId))
                    {
                        this.MessagesQueue.Enqueue(activity);
    
                        foreach (var observer in observers)
                        {
                            observer.OnNext(activity);
                        }
                    }
                }
            });
    
            observers = new List<IObserver<ChatServerRoomActivityInfoBase>>();
        }
    
        ~ChatServerUserSessionInfo()
        {
            Dispose();
        }
    
        public void Dispose()
        {
            if (subscription != null)
            {
                subscription.Dispose();
                subscription = null;
            }
    
            this.observers = null;
    
            GC.SuppressFinalize(this);
        }
    
        public IDisposable Subscribe(IObserver<ChatServerRoomActivityInfoBase> observer)
        {
            lock (parentUserSessions.Lock)
            {
                this.observers.Add(observer);
                return (IDisposable)new Subscription(this, observer);
            }
        }
    
        private void Unsubscribe(IObserver<ChatServerRoomActivityInfoBase> observer)
        {
            lock (parentUserSessions.Lock)
            {
                if (this.observers == null)
                {
                    return;
                }
    
                this.observers.Remove(observer);
            }
        }
    
        private class Subscription : IDisposable
        {
            private ChatServerUserSessionInfo subject;
            private IObserver<ChatServerRoomActivityInfoBase> observer;
    
            public Subscription(ChatServerUserSessionInfo subject, IObserver<ChatServerRoomActivityInfoBase> observer)
            {
                this.subject = subject;
                this.observer = observer;
            }
    
            public void Dispose()
            {
                IObserver<ChatServerRoomActivityInfoBase> observer = Interlocked.Exchange<IObserver<ChatServerRoomActivityInfoBase>>(ref this.observer, (IObserver<ChatServerRoomActivityInfoBase>)null);
                if (observer == null)
                {
                    return;
                }
    
                this.subject.Unsubscribe(observer);
                this.subject = (ChatServerUserSessionInfo)null;
            }
        }
    }
    

    Each user session has own MessageQueue and is subscribed to global chat room activity subject. ChatRoomActivityMessages are persisted for each session individualy. Here is method for retrieving messages:

    public void CheckForChatRoomsActivityAsync(long userId, string userName, Action<List<ChatServerRoomActivityInfoBase>> onChatRoomActivity)
        {
            var sessionId = GetCurrentSessionId();
            var chatServerUserSessions = GetChatServerUserSessions(userId, userName);
    
            lock (chatServerUserSessions.Lock)
            {
                var userSession = GetChatServerUserSessionInfo(sessionId, chatServerUserSessions);
                ProlongSubscriptions(userSession);
    
                if (userSession.MessagesQueue.Count > 0)
                {
                    var activities = new List<ChatServerRoomActivityInfoBase>();
                    while (userSession.MessagesQueue.Count > 0)
                    {
                        activities.Add(userSession.MessagesQueue.Dequeue());
                    }
    
                    onChatRoomActivity(activities);
                }
                else
                {
                    var queued = ThreadPool.QueueUserWorkItem(new WaitCallback(parm =>
                    {
                        var activities = new List<ChatServerRoomActivityInfoBase>();
                        var wait = new AutoResetEvent(false);
    
                        using (var subscriber = userSession.Subscribe(activity =>
                        {
                            lock (chatServerUserSessions.Lock)
                            {
                                activities.Add(activity);
                                userSession.MessagesQueue.Dequeue();
    
                                wait.Set();
                            }
                        }))
                        {
                            wait.WaitOne(TimeSpan.FromSeconds(CheckForActivityMaxWaitSeconds));
                        }
    
                        ((Action<List<ChatServerRoomActivityInfoBase>>)parm)(activities);
                    }), onChatRoomActivity);
    
                    if (!queued)
                    {
                        onChatRoomActivity(new List<ChatServerRoomActivityInfoBase>());
                    }
                }
            }
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm making a simple page using Google Maps API 3. My first. One marker
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
this is what i have right now Drawing an RSS feed into the php,
I am reading a book about Javascript and jQuery and using one of the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.