Esempio n. 1
0
 public static void AsyncLock_Acquire_Timeout()
 {
     using (var l = new AsyncLock())
     {
         var sw = Stopwatch.StartNew();
         using (AsyncLockCookie t1 = l.Acquire())
             using (AsyncLockCookie t2 = l.Acquire(100))
             {
                 Assert.True(t1.IsAcquired);
                 Assert.False(t2.IsAcquired);
                 Assert.True(sw.Elapsed.TotalMilliseconds >= 80);
             }
     }
 }
Esempio n. 2
0
 public static void AsyncLock_Acquire_Twice()
 {
     using (var l = new AsyncLock())
     {
         using (AsyncLockCookie t = l.Acquire())
         {
             Assert.True(t.IsAcquired);
             Assert.Equal(t.IsAcquired, t);
         }
         using (AsyncLockCookie t = l.Acquire())
         {
             Assert.True(t.IsAcquired);
         }
     }
 }
Esempio n. 3
0
        public async Task <T> GetAsync <T>(string key, Func <Task <T> > acquirer, TimeSpan?duration = null)
        {
            T value;

            if (TryGet(key, out value))
            {
                return(value);
            }

            // get the async (semaphore) locker specific to this key
            var keyLock = AsyncLock.Acquire(key);

            using (await keyLock.LockAsync())
            {
                if (!TryGet(key, out value))
                {
                    value = await acquirer().ConfigureAwait(false);

                    Put(key, value, duration);
                    return(value);
                }
            }

            return(value);
        }
Esempio n. 4
0
        public override async ValueTask <T> ReadAsync(CancellationToken token)
        {
            await reader.WaitToReadAsync(token).ConfigureAwait(false);

            //lock and deserialize
            T result;

            using (await readLock.Acquire(token).ConfigureAwait(false))
            {
                var lookup = Partition;
                //reset file cache
                await lookup.FlushAsync(token).ConfigureAwait(false);

                result = await reader.DeserializeAsync(lookup, token).ConfigureAwait(false);

                cursor.Advance(lookup.Position);
            }
            return(result);
        }
Esempio n. 5
0
        public override async ValueTask WriteAsync(T item, CancellationToken token)
        {
            using (await writeLock.Acquire(token).ConfigureAwait(false))
            {
                var partition = Partition;
                await writer.SerializeAsync(item, partition, token).ConfigureAwait(false);

                cursor.Advance(partition.Position);
            }
            writer.MessageReady();
        }
Esempio n. 6
0
        public static void AsyncLock_Acquire_Wait()
        {
            using (var l = new AsyncLock())
            {
                AsyncLockCookie t1 = l.Acquire();
                Assert.True(t1.IsAcquired);

                var sw = Stopwatch.StartNew();
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    Thread.Sleep(500);
                    t1.Dispose();
                });
                using (AsyncLockCookie t2 = l.Acquire())
                {
                    Assert.True(t2);
                }
                Assert.True(sw.Elapsed.TotalMilliseconds >= 400);
            }
        }
Esempio n. 7
0
        public static void AsyncLock_Acquire_Fail()
        {
            using (var l = new AsyncLock())
            {
                using (AsyncLockCookie t1 = l.Acquire())
                {
                    Assert.True(t1.IsAcquired);
                    using (AsyncLockCookie t2 = l.Acquire(0))
                    {
                        Assert.False(t2.IsAcquired);
                        Assert.Equal(t2.IsAcquired, t2);
                    }

                    using (AsyncLockCookie t2 = l.Acquire(TimeSpan.Zero))
                    {
                        Assert.False(t2.IsAcquired);
                        Assert.Equal(t2.IsAcquired, t2);
                    }
                }
            }
        }
Esempio n. 8
0
        public async Task <ulong> GetFileSizeInBytes()
        {
            if (_fileSizeInBytes == null)
            {
                using (await bsf_lock.Acquire())
                {
                    var props = await _backingFile.GetBasicPropertiesAsync();

                    _fileSizeInBytes = props.Size;
                }
            }
            return(_fileSizeInBytes.Value);
        }
 public IExchange DeclareExchange(string exchangeName, string exchangeType)
 {
     if (exchanges.TryGetValue(exchangeName, out var exchange))
     {
         return(exchange);
     }
     using (asyncLock.Acquire())
     {
         if (exchanges.TryGetValue(exchangeName, out exchange))
         {
             return(exchange);
         }
         exchange = advancedBus.ExchangeDeclare(exchangeName, exchangeType);
         exchanges[exchangeName] = exchange;
         return(exchange);
     }
 }
Esempio n. 10
0
        public async Task StopRoamingFile(IBindableStorageFile file)
        {
            using (await f_lock.Acquire())
            {
                if (!LocalFiles.Contains(file))
                {
                    //Backing values
                    string oldPath = GetParentFolder(file.BackingFile);
                    string value   = await _ivService.GetValue(oldPath, FileLocation.Roamed);

                    await _ivService.Remove(oldPath, FileLocation.Roamed);

                    await file.BackingFile.MoveAsync(_localFolder, file.BackingFile.Name, NameCollisionOption.GenerateUniqueName);

                    await _ivService.Add(GetParentFolder(file.BackingFile), value, FileLocation.Local);

                    RoamedFiles.Remove(file);

                    //UI
                    file.IsRoamed = false;
                    LocalFiles.Add(file);
                }
            }
        }
Esempio n. 11
0
        private async Task <ActionResult> HandleImage(
            ProcessImageQuery query,
            CachedImageResult cachedImage,
            string nameWithoutExtension,
            string mime,
            string extension,
            Func <string, Task <byte[]> > getSourceBuffer)
        {
            string prevMime = null;

            if (extension != cachedImage.Extension)
            {
                // The query requests another format.
                // Adjust extension and mime type fo proper ETag creation.
                extension = cachedImage.Extension;
                prevMime  = mime;
                mime      = MimeTypes.MapNameToMimeType(cachedImage.FileName);
            }

            if (cachedImage.Exists)
            {
                if (ETagMatches(nameWithoutExtension, mime, cachedImage.LastModifiedUtc.Value))
                {
                    return(Content(null));
                }
            }

            var isFaulted = false;

            try
            {
                if (!cachedImage.Exists)
                {
                    // get the async (semaphore) locker specific to this key
                    var keyLock = AsyncLock.Acquire("lock" + cachedImage.Path);

                    // Lock concurrent requests to same resource
                    using (await keyLock.LockAsync())
                    {
                        _imageCache.RefreshInfo(cachedImage);

                        // File could have been processed by another request in the meantime, check again.
                        if (!cachedImage.Exists)
                        {
                            // Call inner function
                            byte[] source = await getSourceBuffer(prevMime);

                            if (source == null)
                            {
                                return(NotFound(mime));
                            }

                            source = await ProcessAndPutToCacheAsync(cachedImage, source, query);

                            return(File(source, mime));
                        }
                    }
                }

                if (Request.HttpMethod == "HEAD")
                {
                    return(new HttpStatusCodeResult(200));
                }

                if (cachedImage.IsRemote && !_streamRemoteMedia)
                {
                    // Redirect to existing remote file
                    Response.ContentType = mime;
                    return(Redirect(_imageCache.GetPublicUrl(cachedImage.Path)));
                }
                else
                {
                    // Open existing stream
                    return(File(cachedImage.File.OpenRead(), mime));
                }
            }
            catch (Exception ex)
            {
                isFaulted = true;
                if (!(ex is ProcessImageException))
                {
                    // ProcessImageException is logged already in ImageProcessor
                    Logger.ErrorFormat(ex, "Error processing media file '{0}'.", cachedImage.Path);
                }
                return(new HttpStatusCodeResult(500, ex.Message));
            }
            finally
            {
                if (!isFaulted)
                {
                    FinalizeRequest(nameWithoutExtension, mime, cachedImage.LastModifiedUtc.GetValueOrDefault());
                }
            }
        }