Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make user event handler code thread safe #4

Open
gacardinal opened this issue Jan 16, 2019 · 1 comment
Open

Make user event handler code thread safe #4

gacardinal opened this issue Jan 16, 2019 · 1 comment

Comments

@gacardinal
Copy link
Owner

gacardinal commented Jan 16, 2019

Currently the WebSocketServer class uses the Socket.BeginReceive() method to asynchronously receive data from the client's socket. The use of this method is very good because it allows the server to avoid spawning a Thread for every single client that connects to it, which becomes a bit excessive when more than 5000 clients connect to a server at once and it also allows the server to avoid having to loop trough a list of current sockets (we tried that with the WebSocketPool class and it ended up not working too well because it hogged the CPU way too much).

What BeginReceive() does is spawn a new Thread only when the network card does receive data and triggers an I/O IRQ. This, however, makes it so the event handlers subscribed to the WebSocketServer's events are executed by different threads which makes the library's users' code not thread safe. For instance, let's say a user subscribes the following method to the OnMessage event:

        private static void OnSocketMessage(object sender, WebSocketServerEventArgs args)
        {
            WebSocketServer server = (WebSocketServer) sender;
            Logger.Log("Thread " + Thread.CurrentThread.ManagedThreadId+ " received message : " + args.DataFrame.Plaintext, Logger.LogType.Info);
        }

It will produce the following output
image
(Note the different thread IDs).

It will be necessary to create a new Thread within the WebSocketServer that checks an 'event Queue' (either periodically or based on a synchronization mechanism) and that will be responsible for executing the event handlers to ensure that the code written by the user is thread safe.

@shelbyyyyy
Copy link

@Gaboik Is this still relevant? If not, please delete/close the issue. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants