c# - SignalR IHubContext and thread safety -


in code sample below i've implemented signalr hub supposed implement following functionality:

  • clients may listen changes of foo instances invoking hub's subscribe method bunch of ids treated group names interally
  • unsubscribing works analog invoking unsubscribe
  • the service layer of web application may notify connected clients subcribed appropriate ids (groups) change has occured invoking onfoochanged

is safe use singleton hub context or need fetch every time inside onfoochanged? feedback on implementation of other methods welcome well. i'm new signalr after all.

[export] public class foohub : hub {   private static readonly lazy<ihubcontext> ctx = new lazy<ihubcontext>(     () => globalhost.connectionmanager.gethubcontext<foohub>());    #region client methods     public void subscribe(int[] fooids)   {     foreach(var fooid in fooids)       this.groups.add(this.context.connectionid, fooid.tostring(cultureinfo.invariantculture));   }    public void unsubscribe(int[] fooids)   {     foreach (var fooid in fooids)       this.groups.remove(this.context.connectionid, fooid.tostring(cultureinfo.invariantculture));   }    #endregion // client methods    #region server methods    /// <summary>   /// called service layer when instance of foo has changed   /// </summary>   public static void onfoochanged(int id)   {     ctx.value.clients.group(id.tostring(cultureinfo.invariantculture)).onfoochanged();   }    #endregion // server methods } 

quoting server broadcast tutorial:

there 2 reasons why want context once: getting context expensive operation, , getting once ensures intended order of messages sent clients preserved.

so, in other words: using lazy singleton safe , recommended way this. if you'd new context each time want send client, you'd risk messages being sent in different order expect.

i'm not aware of reason why might want new context regularly.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -