Exemplo n.º 1
0
 /// <summary>Initializes the scheduler.</summary>
 /// <param name="maxConcurrency">The number of threads to create and use for processing work items.</param>
 /// <param name="name">The name to use for each of the created threads.</param>
 protected AbstractTaskScheduler(string name, int maxConcurrency)
 {
     Name = name;
     MaximumConcurrencyLevel = maxConcurrency <= 0 ? Environment.ProcessorCount : maxConcurrency;
     TaskFactory             = new TaskFactory(this);
     Awaiter = new TaskFactoryAwaiter(TaskFactory);
 }
Exemplo n.º 2
0
        static dynamic GetDynamicAwaitableObject(bool completeSynchronously)
        {
            // ExpandoObject类型可在运行时动态添加和删除其成员的对象
            dynamic result  = new ExpandoObject(); // 类型t
            dynamic awaiter = new ExpandoObject(); // 类型A

            awaiter.Message     = "Completed synchronously";
            awaiter.IsCompleted = completeSynchronously;
            awaiter.GetResult   = (Func <string>)(() => awaiter.Message);

            awaiter.OnCompleted = (Action <Action>)(callback => ThreadPool.QueueUserWorkItem(state =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(3));
                awaiter.Message = GetInfo();
                callback?.Invoke();
            }));

            // 使用Impromptu.ActLike方法动态的创建代理对象,该对象将实现任何需要的接口
            IAwaiter <string> proxy = Impromptu.ActLike(awaiter);

            // t有一个名为GetAwaiter的可访问的实例或扩展方法
            result.GetAwaiter = (Func <dynamic>)(() => proxy);

            return(result);
        }
        private Task <T> TakeAsync <TAwaiterFactory>(TAwaiterFactory awaiterFactory) where TAwaiterFactory : IAwaiterFactory <T>
        {
            long balanceAfterCurrentAwaiter = Interlocked.Decrement(ref _queueBalance);

            if (balanceAfterCurrentAwaiter < 0)
            {
                //	Awaiters are dominating, so we can safely add a new awaiter to the queue.
                IAwaiter <T> awaiter = awaiterFactory.CreateAwaiter();
                _awaiterQueue.Enqueue(awaiter);
                return(awaiter.Task);
            }
            else
            {
                //	There's at least one item available or being added, so we're returning it directly.

                T        item;
                SpinWait spin = new SpinWait();

                while (!_itemQueue.TryTake(out item))
                {
                    spin.SpinOnce();
                }

                return(Task.FromResult(item));
            }
        }
Exemplo n.º 4
0
        static dynamic GetDynamicAwaitableObject(bool completeSynchronously)
        {
            dynamic result  = new ExpandoObject();
            dynamic awaiter = new ExpandoObject();

            awaiter.Message     = "Completed synchronously";
            awaiter.IsCompleted = completeSynchronously;
            awaiter.GetResult   = (Func <string>)(() => awaiter.Message);

            awaiter.OnCompleted = (Action <Action>)(callback =>
                                                    ThreadPool.QueueUserWorkItem(state => {
                Thread.Sleep(TimeSpan.FromSeconds(1));
                awaiter.Message = GetInfo();
                if (callback != null)
                {
                    callback();
                }
            })
                                                    );

            IAwaiter <string> proxy = Impromptu.ActLike(awaiter);

            result.GetAwaiter = (Func <dynamic>)(() => proxy);

            return(result);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AwaiterInterfaceWrapper"/> struct.
 /// </summary>
 /// <param name="awaiter">
 /// The awaiter to wrap.
 /// </param>
 public AwaiterInterfaceWrapper(IAwaiter awaiter)
 {
     if (awaiter == null)
     {
         throw new ArgumentNullException(nameof(awaiter));
     }
     this.awaiter = awaiter;
 }
Exemplo n.º 6
0
        public void Update(IServices services)
        {
            EnsureInitialized();

            while (true)
            {
                if (_currentState != null)
                {
                    if (!_currentState.IsCompleted)
                    {
                        return;
                    }

                    _currentState = null;
                }

                if (_currentExecutor != null)
                {
                    while (_currentExecutor.Next(out var current))
                    {
                        if (current == null)
                        {
                            throw new InvalidOperationException();
                        }

                        if (current == BreakAwaitable.Instance)
                        {
                            break;
                        }

                        if (current == SpinAwaitable.Instance)
                        {
                            return;
                        }

                        _currentState = current.GetAwaiter();
                        if (!_currentState.IsCompleted)
                        {
                            return;
                        }
                    }

                    _currentState = null;

                    _currentExecutor.Complete();
                    _currentExecutor = null;
                }

                if (_executionQueue.Count <= 0)
                {
                    break;
                }

                _currentExecutor = _executionQueue.Dequeue();
                _currentExecutor.Execute(services);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates future from specified .Net task.
        /// Completion of this task will await with specified awaiter.
        /// </summary>
        /// <param name="awaiter">A strategy of await task completion.</param>
        /// <param name="task">A task which should be transformed to future.</param>
        /// <typeparam name="T">Type of task result.</typeparam>
        /// <returns>A future which wraps task computation results.</returns>
        public static Future <T> From <T>(IAwaiter awaiter, Task <T> task)
        {
            var promise       = new Promise <T>();
            var awaitableTask = AwaitableTask <T> .Acquire(task, promise);

            awaiter.Await(awaitableTask, awaitableTask);

            return(promise.Future);
        }
Exemplo n.º 8
0
        public TestAgataFutures(int iterations)
        {
            var handler = new HttpClientHandler {
                MaxConnectionsPerServer = 1000
            };

            _client     = new HttpClient(handler);
            _iterations = iterations;
            _awaiter    = new SingleThreadPollTaskAwaiter("Tasks awaiter", ThreadPriority.Normal);
        }
Exemplo n.º 9
0
        protected AwaitableAttachment(SerializationInfo info, StreamingContext context)
        {
            // constructor arguments
            var jsonAttachment = default(string);

            SetField.NotNullFrom(out jsonAttachment, nameof(this.attachment), info);
            this.attachment = JsonConvert.DeserializeObject <Attachment>(jsonAttachment);

            this.awaiter = Awaitable.FromSource(this.attachment, this.ResolveFromSourceAsync) as IAwaiter <Stream>;
        }
Exemplo n.º 10
0
        public void ConfiguredTaskWrapperWithResultCreateAwaiter()
        {
            const int      Value   = 5;
            IAwaiter <int> awaiter = Task.Run(() =>
            {
                Thread.Sleep(50);
                return(Value);
            }).AsITask().ConfigureAwait(false).CreateAwaiter();

            Assert.IsNotNull(awaiter);
        }
Exemplo n.º 11
0
        private void Suspend(Task local, IAwaiter a)
        {
            Move(ref _runningTasks, ref _suspendedTasks, local);

            a.OnCompleted(() =>
            {
                // タイマーとかの OnCompleted 待ちすることもあるので、
                // この中、別スレッドで呼ばれる可能性あり。
                if (_status != TaskSchedulerStatus.ShutdownTimeout)
                {
                    Move(ref _suspendedTasks, ref _runningTasks, local);
                }
            });
        }
Exemplo n.º 12
0
            private IAwaiter <T> SpinUntilAwaiterIsReady(int slot)
            {
                SpinWait spin = new SpinWait();

                while (true)
                {
                    IAwaiter <T> awaiter = Volatile.Read(ref _awaiters[slot]);
                    if (awaiter != null)
                    {
                        return(awaiter);
                    }

                    spin.SpinOnce();
                }
            }
Exemplo n.º 13
0
        public ThreadContext(string name, SynchronizationContext context = null)
        {
            Name    = name;
            Awaiter = new ThreadContextAwaiter(this);

            if (context == null)
            {
                Context = new SynContext(this);
                Context.OperationStarted();
                Task.Run(Execute);
            }
            else
            {
                Context = context;
            }

            Id = Context.GetHashCode();
        }
Exemplo n.º 14
0
        /// <summary>Gets the result of the completed awaited operation.</summary>
        public TResult GetResult()
        {
            if (_asyncOp == null)
            {
                return(_result);
            }

            IAwaiter <TResult> awaiter = _asyncOp as IAwaiter <TResult>;

            if (awaiter != null)
            {
                return(awaiter.GetResult());
            }

            Task <TResult> task = (Task <TResult>)_asyncOp;

            return(task.GetAwaiter().GetResult());
        }
Exemplo n.º 15
0
        /// <summary>Schedules the continuation action that's invoked when the instance completes.</summary>
        /// <param name="continuation">The action to invoke when the operation completes.</param>
        public void UnsafeOnCompleted(Action continuation)
        {
            if (_asyncOp == null)
            {
                Task.Run(continuation);
                return;
            }

            IAwaiter <TResult> awaiter = _asyncOp as IAwaiter <TResult>;

            if (awaiter != null)
            {
                awaiter.UnsafeOnCompleted(continuation);
                return;
            }

            Task <TResult> task = (Task <TResult>)_asyncOp;

            task.GetAwaiter().UnsafeOnCompleted(continuation);
        }
Exemplo n.º 16
0
 //[DebuggerHidden]
 public ETTask(Func <ETTask> factory)
 {
     this.awaiter = new LazyPromise(factory);
 }
Exemplo n.º 17
0
 //[DebuggerHidden]
 public ETTask(IAwaiter awaiter)
 {
     this.awaiter = awaiter;
 }
Exemplo n.º 18
0
 public IsCanceledAwaiter(IAwaiter awaiter)
 {
     this.awaiter = awaiter;
 }
Exemplo n.º 19
0
 public AsyncUnitAwaiter(IAwaiter awaiter)
 {
     this.awaiter = awaiter;
 }
Exemplo n.º 20
0
 public InstanceAwaiterFactory(IAwaiter <T> awaiter)
 {
     _awaiter = awaiter;
 }
Exemplo n.º 21
0
 public UniTask(IAwaiter awaiter)
 {
     this.awaiter = awaiter;
 }
Exemplo n.º 22
0
 public MochiTask(CancellationToken cancellationToken)
 {
     this.objectAwaiter = null;
     this.valueAwaiter  = new Awaiter <T>(cancellationToken);
 }
Exemplo n.º 23
0
        public void TaskWrapperCreateAwaiter()
        {
            IAwaiter awaiter = Task.Run(() => Thread.Sleep(50)).AsITask().CreateAwaiter();

            Assert.IsNotNull(awaiter);
        }
Exemplo n.º 24
0
 public MochiTask(IAwaiter <T> awaiter)
 {
     this.objectAwaiter = awaiter;
     this.valueAwaiter  = default;
 }
Exemplo n.º 25
0
 public ValueAwaiter(IAwaiter <T> awaiter)
 {
     _awaiter = awaiter;
 }
Exemplo n.º 26
0
        public AwaitableAttachment(Attachment attachment)
        {
            this.attachment = attachment;

            this.awaiter = Awaitable.FromSource(attachment, this.ResolveFromSourceAsync) as IAwaiter <Stream>;
        }
Exemplo n.º 27
0
 public MochiTask(Awaiter <T> awaiter)
 {
     this.objectAwaiter = null;
     this.valueAwaiter  = awaiter;
 }
Exemplo n.º 28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AwaiterInterfaceWrapper{TResult}"/> class.
 /// </summary>
 /// <param name="awaiter">
 /// The awaiter to wrap.
 /// </param>
 public AwaiterInterfaceWrapper(IAwaiter <TResult> awaiter)
 {
     this.awaiter = awaiter;
 }
Exemplo n.º 29
0
 public AwaitableWrapper(IAwaiter <T> ia)
 {
     awaitable = ia ?? throw new ArgumentNullException(nameof(ia));
     result    = default(T);
 }
Exemplo n.º 30
0
 public MochiTask(T value)
 {
     this.objectAwaiter = null;
     this.valueAwaiter  = new Awaiter <T>(value);
 }