简体   繁体   中英

Is correct to use transaction inside a Hub on SignalR

I am learning SignalR and I have some doubts about it.

First: Does the Hub works as static object? This question moves to the next question.

Second: Is right to start a transaction inside a method inside the hub?

I want to use the SignalR to send and save information in real time. For example, I want to create a chat, and, when the server receive the message, it saves in the database.

My question is about the method that receive the message will be in memory forever (while the webapp is running).

My concern is about the transaction/connection. Does the transaction will be always active?

For example:

public void Send(string name, string message)
        {
             Message m = new Message() { n = name, m = message};
             using(Entities db = new Entities()
             {
                 db.Messages.Add(m);
                 db.Save();
             } 
            // Call the addNewMessageToPage method to update clients.
            Clients.All.addNewMessageToPage(name, message);
        }

I am using EntityFramework 6 and SignalR 2.

Hub instances are created for each request. You can read more about hub instance lifetime here . EF is creating a transaction each time it needs to save changes. However the transactions created by EF are committed/rolled back and disposed once saving changes is completed and transactions do not leak outside the SaveChanges call. You are also disposing your context (which is good) so you do not leak transactions or connections. (I actually don't hub instance lifetime is relevant at all in your case since you don't try to store anything in class variables).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM