sta / websocket-sharp

A C# implementation of the WebSocket protocol client and server
http://sta.github.io/websocket-sharp
MIT License
5.71k stars 1.66k forks source link

Thread-safety in event handlers #55

Open reverofevil opened 10 years ago

reverofevil commented 10 years ago

I have a user UI on Android. I'm trying to set contents of text field to the value of the message received via WebSockets. The problem is that onMessage handler is called in an another thread, while UI controls on Android are not thread-safe.

Is it possible to wrap it inside websocket-sharp to avoid such behaviour?

sta commented 10 years ago

Is it possible to wrap it inside websocket-sharp to avoid such behaviour?

Nope, but maybe Example is helpful to you.

Is it possible to pull received data from temporary data queue, in the UI thread?

reverofevil commented 10 years ago

@sta That's exactly what I do: use RunOnUiThread. This looks inferior to implementation of websockets in Node.js, because I have to use a callback with RunOnUiThread with yet another callback inside. That just doesn't look good to me. Isn't it possible to interrupt execution of the thread from which websocket object was created, run some code there, and return to the previous computation?

sta commented 10 years ago

Have you developed your apps with Xamarin?

And, do you mean that the following doesn't work?

// In a class that inherits the Android.App.Activity class.
ws.OnMessage += (sender, e) => {
  RunOnUiThread (
    () => {
      // Do something with e.Data (or e.RawData) and UI controls.
      ...
    });
};

Could you show me WebSocket part of your apps?

Isn't it possible to interrupt execution of the thread from which websocket object was created...

Nope (though I don't know what you mean correctly).

reverofevil commented 10 years ago

Yep, Xamarin. The code you posted is exactly what I did. The thing I don't like is that when one is making app with Node.js, there's no need to wrap the code with RunOnWhateverThread, though internally there's a thread pool to work with network/file system/etc asynchronously too. It would be much better to do it like that.

As far as I understand, while thread pool of websocket-sharp keeps working, the UI thread keeps working too. If one wants to run callback code in the UI thread, he has to interrupt execution of the code in UI thread temporary and run the callback (patched stack, like in coroutines). There's a support of fibers in CLR in .NET 2.0+, so it should be possible to do that anyway. Isn't BackgroundWorker a solution?

(I have approximately a week of C# experience, so I cannot say correctly how to implement that.)