/// <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); }
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)); } }
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); }
/// <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; }
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); } }
/// <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); }
public TestAgataFutures(int iterations) { var handler = new HttpClientHandler { MaxConnectionsPerServer = 1000 }; _client = new HttpClient(handler); _iterations = iterations; _awaiter = new SingleThreadPollTaskAwaiter("Tasks awaiter", ThreadPriority.Normal); }
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>; }
public void ConfiguredTaskWrapperWithResultCreateAwaiter() { const int Value = 5; IAwaiter <int> awaiter = Task.Run(() => { Thread.Sleep(50); return(Value); }).AsITask().ConfigureAwait(false).CreateAwaiter(); Assert.IsNotNull(awaiter); }
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); } }); }
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(); } }
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(); }
/// <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()); }
/// <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); }
//[DebuggerHidden] public ETTask(Func <ETTask> factory) { this.awaiter = new LazyPromise(factory); }
//[DebuggerHidden] public ETTask(IAwaiter awaiter) { this.awaiter = awaiter; }
public IsCanceledAwaiter(IAwaiter awaiter) { this.awaiter = awaiter; }
public AsyncUnitAwaiter(IAwaiter awaiter) { this.awaiter = awaiter; }
public InstanceAwaiterFactory(IAwaiter <T> awaiter) { _awaiter = awaiter; }
public UniTask(IAwaiter awaiter) { this.awaiter = awaiter; }
public MochiTask(CancellationToken cancellationToken) { this.objectAwaiter = null; this.valueAwaiter = new Awaiter <T>(cancellationToken); }
public void TaskWrapperCreateAwaiter() { IAwaiter awaiter = Task.Run(() => Thread.Sleep(50)).AsITask().CreateAwaiter(); Assert.IsNotNull(awaiter); }
public MochiTask(IAwaiter <T> awaiter) { this.objectAwaiter = awaiter; this.valueAwaiter = default; }
public ValueAwaiter(IAwaiter <T> awaiter) { _awaiter = awaiter; }
public AwaitableAttachment(Attachment attachment) { this.attachment = attachment; this.awaiter = Awaitable.FromSource(attachment, this.ResolveFromSourceAsync) as IAwaiter <Stream>; }
public MochiTask(Awaiter <T> awaiter) { this.objectAwaiter = null; this.valueAwaiter = awaiter; }
/// <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; }
public AwaitableWrapper(IAwaiter <T> ia) { awaitable = ia ?? throw new ArgumentNullException(nameof(ia)); result = default(T); }
public MochiTask(T value) { this.objectAwaiter = null; this.valueAwaiter = new Awaiter <T>(value); }