onLineNames.Add(chatName);
}
SendMessage(chatName, "大家好,我进入聊天室了!", status);
return new { success = true, info = string.Empty };
}
else
{
lock (syncObject1)
{
onLineNames.Remove(chatName);
}
SendMessage(chatName, "再见,我离开聊天室了!", status);
return new { success = true, info = string.Empty };
}
}
/// <summary>
/// 获取未读的新消息
/// </summary>
/// <param name="chatName"></param>
/// <returns></returns>
private object GetNewMessages(string chatName)
{
//第一种:循环处理
while (true)
{
var newMsgs = msgs.Where(m => m.name != chatName && !(m.readednams ?? "").Contains(chatName)).OrderBy(m => m.sendtime).ToList();
if (newMsgs != null && newMsgs.Count() > 0)
{
lock (syncObject)
{
newMsgs.ForEach((m) =>
{
m.readednams += chatName + ",";
m.readedCount++;
});
int chatNameCount = onLineNames.Count();
msgs.RemoveAll(m => m.readedCount >= chatNameCount);
}
return new { success = true, msgs = newMsgs };
}
Thread.Sleep(1000);
}
//第二种方法,采用自旋锁
//List<Msg> newMsgs = null;
//SpinWait.SpinUntil(() =>
//{
// newMsgs = msgs.Where(m => m.name != chatName && !(m.readednams ?? "").Contains(chatName)).OrderBy(m => m.sendtime).ToList();
// return newMsgs.Count() > 0;
//}, -1);
//rwLock.EnterWriteLock();
//newMsgs.ForEach(m =>