Beispiel #1
0
        protected override async Task <Tuple <bool, JObject> > TryObtainLockAsync(string lockMessage, CancellationToken token)
        {
            // Create the feedlock file if it doesn't exist, this will stay around indefinitely. The lock is done
            // by leasing this file.
            await CreateFileIfNotExistsAsync();

            // Try to lease the blob
            var result = await _lease.GetLease();

            if (result)
            {
                // Keep the lease
                if (_keepLockTask == null)
                {
                    _keepLockTask = Task.Run(async() => await KeepLock());
                }

                // For azure blobs the message goes into a separate file.
                var json = GetMessageJson(lockMessage);
                _updateLockMessage = _messageBlob.UploadTextAsync(json.ToString());

                // The message is not needed for success
                return(Tuple.Create(result, new JObject()));
            }
            else
            {
                // Return a non-successful result along with the message from the other client locking this feed if one exists.
                var json = await GetMessageJson();

                return(Tuple.Create(result, json));
            }
        }
Beispiel #2
0
        public async Task <bool> GetLock(TimeSpan wait, CancellationToken token)
        {
            var result = false;

            if (!_isLocked)
            {
                var exists = await _blob.ExistsAsync();

                if (!exists)
                {
                    // Create the feed lock blob if it doesn't exist
                    var bytes = Encoding.UTF8.GetBytes("feedlock");
                    await _blob.UploadFromByteArrayAsync(bytes, 0, bytes.Length);
                }

                var timer = new Stopwatch();
                timer.Start();

                var lastNotify = TimeSpan.Zero;
                var firstLoop  = true;

                do
                {
                    result = await _lease.GetLease();

                    if (!result)
                    {
                        var diff = timer.Elapsed.Subtract(lastNotify);

                        if (diff.TotalSeconds > 60 || firstLoop)
                        {
                            _log.LogMinimal($"Waiting to obtain an exclusive lock on the feed.");
                        }

                        firstLoop = false;
                        await Task.Delay(100);
                    }
                }while (!result && timer.Elapsed < wait);

                if (!result)
                {
                    _log.LogError($"Unable to obtain a lock on the feed. Try again later.");
                }
                else if (_keepLockTask == null)
                {
                    _keepLockTask = Task.Run(async() => await KeepLock());
                }

                _isLocked = result;
            }

            return(result);
        }