我有一个基本功能,如下所示:
public void AllDataUpdated()
{
Clients.Others.allDataUpdated();
}
现在,我希望在每次调用之间添加半秒延迟。但是,我不想在这样做时锁定我的网络服务器。
我的第一直觉是做以下事情:
async Task SendWithDelay(var other, var timeout)
{
await Task.Delay(timeout);
other.allDataUpdated();
}
并在我的public void AllDataUpdated()
函数中互相迭代,并为每次迭代增加超时。这是正确的方法吗?我应该如何以不会使用此过程锁定我的网络服务器的方式执行此操作,但会错开SignalR的发射?
谢谢!
编辑:我想要的结果是client_0在0毫秒收到此消息,然后client_1在500毫秒时收到消息,等等。所有呼叫都来自AllDataUpdated()
。
答案 0 :(得分:0)
// synchronization primitive
private readonly object syncRoot = new object();
// the timer for 500 miliseconds delay
private Timer notificator;
// public function used for notification with delay
public void NotifyAllDataUpdatedWithDelay() {
// first, we need claim lock, because of accessing from multiple threads
lock(this.syncRoot) {
if (null == notificator) {
// notification timer is lazy-loaded
notificator = new Timer(500);
notificator.Elapse += notificator_Elapsed;
}
if (false == notificator.Enabled) {
// timer is not enabled (=no notification is in delay)
// enabling = starting the timer
notificator.Enabled = true;
}
}
}
private void notificator_Elapsed(object sender, ElapsedEventArgs e) {
// first, we need claim lock, because of accessing from multiple threads
lock(this.syncRoot) {
// stop the notificator
notificator.Enabled = false;
}
// notify clients
Clients.Others.allDataUpdated();
}