我正在嘗試顯示用戶的在線朋友。爲此,我在UserInfo
表中創建了一個OnlineStatus
列。我創建了一個集線器,它在開始時調用一個函數,該函數向服務器發送一個Ajax請求以獲取在線朋友列表。如果該用戶的一位朋友登錄,OnlineStatus將被設置爲1,否則爲0.爲了讓用戶實時看到他的在線朋友,我使用了SqlDependency,如果OnlineStatus列被更新並且SiganlR調用集線器的功能,轉而調用Client的函數,該函數依次向服務器發送Ajax請求,請求更新的在線用戶列表。 Hub在開始時工作正常,但是如果用戶註銷並且SqlDependency沒有被調用。請幫我解決它。 這裏是行動:如果表已更新,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();
}
}