简体   繁体   English

在SignalR上的集线器内使用事务是正确的

[英]Is correct to use transaction inside a Hub on SignalR

I am learning SignalR and I have some doubts about it. 我正在学习SignalR,对此有些疑问。

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. 我想使用SignalR实时发送和保存信息。 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). 我的问题是关于接收消息的方法将永远存在于内存中(当webapp运行时)。

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. 我正在使用EntityFramework 6和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. EF每次需要保存更改时都会创建一个事务。 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. 但是,一旦保存更改完成且事务不会泄漏到SaveChanges调用之外,则EF所创建的事务将被提交/回滚并处置。 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). (实际上,集线器实例生存期与您的情况根本无关,因为您不尝试在类变量中存储任何内容)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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