/// <inheritdoc />
            public override bool Enter(TimeSpan timeout, CancellationToken cancellationToken)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(false);
                }

                if (timeout == TimeSpan.Zero)
                {
                    return(locker.Do(() =>
                    {
                        if (!locked)
                        {
                            locked = true;
                            ev.Reset();
                            return true;
                        }
                        return false;
                    }));
                }

                var stopwatch = Stopwatch.StartNew();

                while (true)
                {
                    if (!locker.Do(() =>
                    {
                        var locked = this.locked;
                        this.locked = true;
                        if (!locked)
                        {
                            ev.Reset();
                        }
                        return(locked);
                    }))
                    {
                        return(true);
                    }

                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(false);
                    }

                    if (timeout != Timeout.InfiniteTimeSpan && stopwatch.Elapsed >= timeout)
                    {
                        return(false);
                    }

                    ev.Wait(GetTimeout(timeout, stopwatch.Elapsed), cancellationToken);
                }
            }
Exemplo n.º 2
0
        public void Complete(bool result)
        {
            if (Interlocked.Exchange(ref completed, 1) == 0)
            {
                disposing.Do(() =>
                {
                    ev.ReleaseAll();

                    this.result = result;
                    continuation?.Invoke();
                });
            }
        }
 public bool Wait(TimeSpan timeout, CancellationToken cancellationToken)
 {
     return(locker.Do(() =>
     {
         if (!released)
         {
             var ev = new T();
             ev.Enter();
             queue.Enqueue(ev);
             return ev;
         }
         return null;
     })?.Enter(timeout, cancellationToken) ?? false);
 }
 public static void Do(this MiniLocker @this, Action action)
 => @this.Do(() => { action(); return(0); });