我正在尝试向用户显示在线朋友。为此,我在OnlineStatus
表中创建了一个列UserInfo
。我创建了一个集线器,在启动时调用一个函数,该函数向服务器发送Ajax请求以获取在线朋友列表。如果该用户的朋友登录,则OnlineStatus将被设置为1,否则为0.如果用户实时看到他的在线朋友,我将使用SqlDependency,如果OnlineStatus列已更新,SiganlR将调用hub的功能,其中转向调用客户端的功能,该功能又向服务器发送Ajax请求,请求更新的在线用户列表。 Hub,一开始,工作正常但是如果用户注销并且没有调用SqlDependency。请帮我修理一下。
这是行动:
Public JsonResult FindOnlineFriends(long UserId)
{
List<UserDetails> onlinefriends = new List<UserDetails>();
using(SqlConnection con=new SqlConnection(connectionString))
{
using(SqlCommand cmd=new SqlCommand())
{
StringBuilder builder = new StringBuilder();
builder.Append("select [UserId],[DisplayPhoto],[Name] from [dbo].[UserInfo] as userself,(");
builder.Append("(select [PersonId2] from [dbo].[FriendsRelation] where [PersonId1] like @UserId) union");
builder.Append("(select [PersonId1] from [FriendsRelation] where [PersonId2] like @UserId)) as friends ");
builder.Append("where [userself].[UserId]=[PersonId2] and [OnlineStatus]=1");
cmd.CommandText = builder.ToString();
cmd.Connection = con;
cmd.Parameters.AddWithValue("@UserId",UserId);
cmd.Notification = null;
SqlDependency.Stop(connectionString);
SqlDependency.Start(connectionString);
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += new OnChangeEventHandler(onlineFriends_OnChange);
con.Open();
using(SqlDataReader rdr=cmd.ExecuteReader())
{
if(rdr.HasRows)
{
while(rdr.Read())
{
onlinefriends.Add(new UserDetails { UserId = Convert.ToInt64(rdr["UserId"]), Name = rdr["Name"].ToString(), DisplayPhoto = rdr["DisplayPhoto"].ToString() });
}
}
}
}
}
return Json(onlinefriends,JsonRequestBehavior.AllowGet);
}
private void onlineFriends_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
SocialNetworkHub.SocialNetworkHub.ShowOnlineFriends();
}
}
答案 0 :(得分:0)
您的解决方案仅适用于一个用户。当您致电SqlDependency.Start()
或SqlDependency.Stop()
时,它会删除所有订阅。但是,对于您的任务,最好使用SqlDependency
- SqlDependencyEx
的开源实现,因为使用此组件,您可以独立监视UPDATE
表的UserInfo
更改。代码示例:
int changesReceived = 0;
using (SqlDependencyEx sqlDependency = new SqlDependencyEx(
TEST_CONNECTION_STRING, TEST_DATABASE_NAME, TEST_TABLE_NAME))
{
sqlDependency.TableChanged += (o, e) => changesReceived++;
sqlDependency.Start();
// Make table changes.
MakeTableInsertDeleteChanges(changesCount);
// Wait a little bit to receive all changes.
Thread.Sleep(1000);
}
Assert.AreEqual(changesCount, changesReceived);
希望这有帮助。