public void UnSubscribeDataChanges(string path, IZKDataListener dataListener) { ConcurrentHashSet <IZKDataListener> listeners; _dataListeners.TryGetValue(path, out listeners); if (listeners != null) { listeners.Remove(dataListener); } if (listeners == null || listeners.IsEmpty) { ConcurrentHashSet <IZKDataListener> _listeners; _dataListeners.TryRemove(path, out _listeners); } }
public void SubscribeDataChanges(string path, IZKDataListener listener) { ConcurrentHashSet <IZKDataListener> listeners; //Monitor.Enter(_dataListener); _dataListener.TryGetValue(path, out listeners); if (listeners == null) { listeners = new ConcurrentHashSet <IZKDataListener>(); _dataListener.TryAdd(path, listeners); } listeners.Add(listener); //Monitor.Exit(_dataListener); WatchForData(path); LOG.Debug("Subscribed data changes for " + path); }
public void SubscribeDataChanges(string path, IZKDataListener listener) { ConcurrentHashSet <IZKDataListener> listeners; _dataListeners.TryGetValue(path, out listeners); if (listeners == null) { listeners = new ConcurrentHashSet <IZKDataListener>(); _dataListeners.TryAdd(path, listeners); } listeners.Add(listener); Task.Run(async() => { await WatchForDataAsync(path); }).ConfigureAwait(false).GetAwaiter().GetResult(); LOG.Debug($"Subscribed data changes for {path}"); }
public ZKDistributedDelayLock(ZKClient client, string lockPach) { this.client = client; this.lockPath = lockPach; cancellationTokenSource = new CancellationTokenSource(); factory = new TaskFactory( cancellationTokenSource.Token, TaskCreationOptions.None, TaskContinuationOptions.None, new LimitedConcurrencyLevelTaskScheduler(1)); nodeListener = new ZKDataListener().DataDeleted( (path) => { factory.StartNew(() => { if (!factory.CancellationToken.IsCancellationRequested) { if (!hasLock) { //如果当前没有持有锁 //为了解决网络闪断问题,先等待一段时间,再重新竞争锁 Thread.Sleep(delayTimeMillis); //如果之前获得锁的线程解除了锁定,则所有等待的线程都重新尝试,这里使得信号量加1 semaphore.Release(); } } }, factory.CancellationToken); }); stateListener = new ZKStateListener().StateChanged((state) => { if (state == KeeperState.SyncConnected) { //如果重新连接 factory.StartNew(() => { if (!factory.CancellationToken.IsCancellationRequested) { if (hasLock) { //现在持有锁 //重新创建节点 try { client.Create(lockPath + "/lock", lockNodeData, CreateMode.Ephemeral); } catch (ZKNodeExistsException e) { try { if (lockNodeData != client.ReadData <string>(lockPath + "/lock")) { hasLock = false; } } catch (ZKNoNodeException e2) { //ignore } } } } }, factory.CancellationToken); } }); }