C# 如何:错开SignalR客户端。C中的其他。[函数]调用
我有一个基本函数,如下所示:C# 如何:错开SignalR客户端。C中的其他。[函数]调用,c#,asynchronous,signalr,async-await,C#,Asynchronous,Signalr,Async Await,我有一个基本函数,如下所示: public void AllDataUpdated() { Clients.Others.allDataUpdated(); } 现在,我想在每个呼叫之间增加半秒的延迟。但是,我不想在这样做时锁定我的web服务器 我的第一反应是做以下事情: async Task SendWithDelay(var other, var timeout) { await Task.Delay(timeout); other.allDataUpdated()
public void AllDataUpdated()
{
Clients.Others.allDataUpdated();
}
现在,我想在每个呼叫之间增加半秒的延迟。但是,我不想在这样做时锁定我的web服务器
我的第一反应是做以下事情:
async Task SendWithDelay(var other, var timeout)
{
await Task.Delay(timeout);
other.allDataUpdated();
}
并在公共void AllDataUpdated函数中相互迭代,并增加每次迭代的超时。这是正确的方法吗?我应该如何做到这一点,而不是用这个过程锁定我的Web服务器,而是错开信号器的发射
谢谢
编辑:我想要的结果是,客户端0在0毫秒时收到此消息,然后客户端1在500毫秒时收到此消息,等等。所有这些都来自对AllDataUpdate的同一个调用。感谢此代码示例,但这不会发送AllDataUpdate;一次发送给所有客户?我期望的结果是,客户端0在0毫秒时收到该消息,然后客户端1在500毫秒时收到该消息,以此类推。因此,如果有100个客户端,最后一个客户端将在50秒后收到通知?是的,这是期望的行为。时间间隔可能会改变,但我们希望通知是交错的。
// 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();
}