protected override void Given()
 {
     TaskSource = Substitute.For<TaskSource>();
     ExecTaskGenerator = Substitute.For<ExecTaskGenerator>();
     Pipeline = new Pipeline(TaskSource, ExecTaskGenerator);
     ObservingEvents();
 }
        public async Task <StorageFile> EnqueueFileDownload(StorageFolder root, Uri uri, string extension = "")
        {
            var filename = Path.GetFileName(uri.LocalPath) + extension;

            var file = await root.TryGetFileAsync(filename).ConfigureAwait(false);

            if (file != null)
            {
                return(file);
            }

            var tcs = new TaskCompletionSource <StorageFile>();

            var taskSource = new TaskSource {
                uri = uri, folder = root, filename = filename, tcs = tcs
            };

            lock (HolderLock)
            {
                if (Stack.Count == 0 && Queue.Count < FIFO_THRESHOLD)
                {
                    Queue.Enqueue(taskSource);
                }
                else
                {
                    Stack.Push(taskSource);
                }
            }
            TryRunTask();
            return(await tcs.Task.ConfigureAwait(false));
        }
        public void BasicTest()
        {
            var ts = TaskSource.New <int>(TaskCreationOptions.None);

            ts.Task.IsCompleted.Should().BeFalse();
            ts.SetResult(1);
            ts.TrySetResult(2).Should().BeFalse();
            ts.Task.IsCompletedSuccessfully().Should().BeTrue();
            ts.Task.Result.Should().Be(1);

            ts = TaskSource.New <int>(TaskCreationOptions.None);
            ts.Task.IsCompleted.Should().BeFalse();
            var e = new InvalidOperationException();

            ts.SetException(e);
            ts.TrySetException(new InvalidOperationException()).Should().BeFalse();
            ts.Task.IsCompleted.Should().BeTrue();
            ts.Task.IsFaulted.Should().BeTrue();
            ts.Task.Exception.Should().NotBeNull();

            ts = TaskSource.New <int>(TaskCreationOptions.None);
            ts.Task.IsCompleted.Should().BeFalse();
            using var cts = new CancellationTokenSource();
            ts.SetCanceled();
            ts.TrySetCanceled(cts.Token).Should().BeFalse();
            ts.Task.IsCompleted.Should().BeTrue();
            ts.Task.IsFaulted.Should().BeFalse();
            ts.Task.IsCanceled.Should().BeTrue();
        }
Exemple #4
0
 internal WhenInvalidatedClosure(TaskSource <Unit> taskSource, IComputed computed, CancellationToken cancellationToken)
 {
     _taskSource                    = taskSource;
     _computed                      = computed;
     _onInvalidatedHandler          = OnInvalidated;
     _computed.Invalidated         += _onInvalidatedHandler;
     _cancellationTokenRegistration = cancellationToken.Register(OnUnregister);
 }
Exemple #5
0
 private void Reset()
 {
     _nextMessageTask = TaskSource.New <RedisValue>(true).Task;
     if (IsDisposeStarted)
     {
         TaskSource.For(_nextMessageTask).TrySetCanceled();
     }
 }
 public static void Run([BlobTrigger(BlobPath)] BlobBaseClient blob,
                        string blobTrigger, Uri uri, BlobProperties properties, IDictionary <string, string> metadata)
 {
     TaskSource.TrySetResult(blob);
     BlobTrigger = blobTrigger;
     Uri         = uri;
     Properties  = properties;
     Metadata    = metadata;
 }
Exemple #7
0
        public SyncAction(OperationQueue operationQueue, IMobileServiceLocalStore store, CancellationToken cancellationToken)
        {
            this.OperationQueue    = operationQueue;
            this.Store             = store;
            this.TaskSource        = new TaskCompletionSource <object>();
            this.CancellationToken = cancellationToken;

            cancellationToken.Register(() => TaskSource.TrySetCanceled());
        }
Exemple #8
0
        public static Task InvalidatedAsync <T>(this IComputed <T> computed, CancellationToken cancellationToken = default)
        {
            if (computed.State == ComputedState.Invalidated)
            {
                return(Task.CompletedTask);
            }
            var ts = TaskSource.New <Unit>(true);

            computed.Invalidated += c => ts.SetResult(default);
        private static TaskCompletionSource <T> Create <T>(SourceOrign origin)
        {
            switch (origin)
            {
            case SourceOrign.NewTCS: return(new TaskCompletionSource <T>());

            case SourceOrign.Create: return(TaskSource.Create <T>(null));

            default: throw new ArgumentOutOfRangeException(nameof(origin));
            }
        }
Exemple #10
0
 public StateSnapshot(IState <T> state, IComputed <T> computed)
 {
     State    = state;
     Computed = computed;
     LatestNonErrorComputed = computed;
     WhenUpdatingSource     = TaskSource.New <Unit>(true);
     WhenUpdatedSource      = TaskSource.New <Unit>(true);
     UpdateCount            = 0;
     ErrorCount             = 0;
     RetryCount             = 0;
 }
Exemple #11
0
 public bool TryCancel(CancellationToken cancellationToken = default)
 {
     if (CancellationToken.IsCancellationRequested)
     {
         TaskSource.For(OutputTask).TrySetCanceled(CancellationToken);
     }
     else if (cancellationToken.IsCancellationRequested)
     {
         TaskSource.For(OutputTask).TrySetCanceled(cancellationToken);
     }
     return(OutputTask.IsCanceled);
 }
 protected override void Given()
 {
     task1 = Substitute.For<TaskSource>();
     bool stop;
     task1.Detect(Arg.Any<string>(), out stop).Returns(info =>
         {
             info[1] = true;
             return new List<TaskDescription>();
         });
     task2 = Substitute.For<TaskSource>();
     compoundTaskSource = new CompoundTaskSource(task1, task2);
 }
        public void VerifyIsSyncSafe(SourceOrign origin)
        {
            var source = Create <int>(origin);

            // Yes this looks stupid, but it's the proper pattern for how we statically init now
            // ...and if we're dropping NET45 support, we can just nuke it all.
#if NET462
            Assert.True(TaskSource.IsSyncSafe(source.Task));
#elif NETCOREAPP2_0
            Assert.True(TaskSource.IsSyncSafe(source.Task));
#endif
        }
Exemple #14
0
        protected async ValueTask <Releaser> FastInternalLockAsync(
            ReentryCounter?reentryCounter, CancellationToken cancellationToken = default)
        {
            var newLockSrc       = TaskSource.New <Unit>(_taskCreationOptions);
            var cancellationTask = (Task?)null;

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();
                if (reentryCounter?.TryReenter(ReentryMode) == true)
                {
                    return(new Releaser(this, default, reentryCounter));
Exemple #15
0
        protected static void EndDelay(ref Task <Unit> task, TimeSpan withDelay = default)
        {
            var newTask = TaskSource.New <Unit>(true).Task;
            var oldTask = Interlocked.Exchange(ref task, newTask);

            if (oldTask == null)
            {
                return;
            }
            if (withDelay == default)
            {
                TaskSource.For(oldTask).SetResult(default);
Exemple #16
0
    // ToTask (typed)

    public static Disposable <Task <T>, CancellationTokenRegistration> ToTask <T>(
        this CancellationToken token,
        TaskCreationOptions taskCreationOptions = default)
    {
        var ts = TaskSource.New <T>(taskCreationOptions);
        var r  = token.Register(() => ts.SetCanceled(token));

#if NETSTANDARD
        return(Disposable.New(ts.Task, r, (_, r1) => r1.Dispose()));
#else
        return(Disposable.New(ts.Task, r, (_, r1) => r1.Unregister()));
#endif
    }
 protected override void Given()
 {
     customTasks = new CustomTasksDetector(taskFileFinder, s => @"{ pipeline: [{
     stage : ""Build"",
        tasks : [""task 1"", ""task 2""]
     },
     {
     stage : ""Deploy to staging"",
     tasks : [""task 3"", ""task 4""]
     }]}
     ");
     taskFileFinder.FindFiles("basefolder").Returns(As.List("runz.me"));
 }
Exemple #18
0
        protected async ValueTask <Releaser> FastInternalLock(
            ReentryCounter?reentryCounter, CancellationToken cancellationToken = default)
        {
            var newLockSrc             = TaskSource.New <Unit>(_taskCreationOptions);
            var dCancellationTokenTask = new Disposable <Task, CancellationTokenRegistration>();

            try {
                for (;;)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    if (reentryCounter?.TryReenter(ReentryMode) == true)
                    {
                        return(new Releaser(this, default, reentryCounter));
        TaskSource RemoveOrStartTask(QueryETag etag)
        {
            lock (_tasksByETag)
            {
                if (!_tasksByETag.Remove(etag, out var task))
                {
                    task = new TaskSource();

                    _tasksByETag[etag] = task;
                }

                return(task);
            }
        }
Exemple #20
0
        public void ExecuteTasks()
        {
            var context     = ContextFactory.CreateEntitiesContext();
            var taskManager = context.GetManager <TaskManager>();
            var task1       = new TaskSource();

            for (int i = 0; i < 10; i++)
            {
                taskManager.ScheduleFrom(task1);
                taskManager.Wait();
//                Assert.AreEqual(1000, task1.sum);
            }
            context.Dispose();
        }
Exemple #21
0
    // (Try)SetFromTask

    public static void SetFromTask <T>(this TaskSource <T> target, Task <T> source, CancellationToken candidateToken)
    {
        if (source.IsCanceled)
        {
            target.SetCanceled(candidateToken.IsCancellationRequested ? candidateToken : CancellationToken.None);
        }
        else if (source.Exception != null)
        {
            target.SetException(source.Exception);
        }
        else
        {
            target.SetResult(source.Result);
        }
    }
Exemple #22
0
    // (Try)SetFromResult

    public static void SetFromResult <T>(this TaskSource <T> target, Result <T> source, CancellationToken candidateToken)
    {
        if (source.IsValue(out var v, out var e))
        {
            target.SetResult(v);
        }
        else if (e is OperationCanceledException && candidateToken.IsCancellationRequested)
        {
            target.SetCanceled(candidateToken);
        }
        else
        {
            target.SetException(e);
        }
    }
        public void CancelDelays(bool immediately = false)
        {
            if (!immediately)
            {
                Clock
                .DelayAsync(CancelDelaysDelay, CancellationToken.None)
                .ContinueWith(_ => CancelDelays(true));
                return;
            }
            var newTask = TaskSource.New <Unit>(true).Task;
            var oldTask = Interlocked.Exchange(ref _cancelDelaysTask, newTask);

            if (oldTask != null)
            {
                TaskSource.For(oldTask).SetResult(default);
Exemple #24
0
        //
        // Points
        //

        public void Enqueue(TimelinePoint point)
        {
            lock (_queue)
            {
                if (_resumeQueue == null && _pendingDequeue != null)
                {
                    _pendingDequeue.SetResult(point);
                    _pendingDequeue = null;
                }
                else
                {
                    _queue.Enqueue(point);
                }
            }
        }
Exemple #25
0
        public void CancelDelays(TimeSpan?cancellationDelay = null)
        {
            var delay = Math.Max(0, (cancellationDelay ?? CancellationDelay).TotalSeconds);

            if (delay > 0)
            {
                Clock.DelayAsync(TimeSpan.FromSeconds(delay)).ContinueWith(_ => CancelDelays(TimeSpan.Zero));
                return;
            }
            var newTask = TaskSource.New <Unit>(true).Task;
            var oldTask = Interlocked.Exchange(ref _cancelDelaysTask, newTask);

            if (oldTask != null)
            {
                TaskSource.For(oldTask).SetResult(default);
Exemple #26
0
        async Task ConnectInitially()
        {
            _connectInitially = new TaskSource();

            try
            {
                await Connection.ConnectAsync();

                await _connectInitially.Task;
            }
            finally
            {
                _connectInitially = null;
            }
        }
Exemple #27
0
        /// <summary>
        /// Asynchronously download thumbnail image and return local storage file.
        /// </summary>
        /// <param name="uuid">UUID of the target device.</param>
        /// <param name="content">Source of thumbnail image.</param>
        /// <returns>Local storage file</returns>
        public async Task <StorageFile> LoadCacheFileAsync(string uuid, ContentInfo content)
        {
            var uri       = new Uri(content.ThumbnailUrl);
            var directory = uuid.Replace(":", "-") + "/";
            var filename  = content.CreatedTime.Replace(":", "-").Replace("/", "-") + "--" + Path.GetFileName(uri.LocalPath);

            if (!filename.Contains("."))
            {
                filename += ".jpg";
            }
            else if (filename.EndsWith(".arw", StringComparison.OrdinalIgnoreCase))
            {
                filename = filename.Substring(0, filename.Length - 3) + "jpg";
            }

            DebugUtil.LogSensitive(() => "Loading {0} into {1}", content.ThumbnailUrl, directory);

            await LoadCacheRoot().ConfigureAwait(false);

            var folder = await CacheFolder.CreateFolderAsync(directory, CreationCollisionOption.OpenIfExists);

            var file = await folder.TryGetFileAsync(filename).ConfigureAwait(false);

            if (file != null)
            {
                return(file);
            }

            var tcs = new TaskCompletionSource <StorageFile>();

            var taskSource = new TaskSource {
                uri = uri, folder = folder, filename = filename, tcs = tcs
            };

            lock (HolderLock)
            {
                if (Stack.Count == 0 && Queue.Count < FIFO_THRESHOLD)
                {
                    Queue.Enqueue(taskSource);
                }
                else
                {
                    Stack.Push(taskSource);
                }
            }
            TryRunTask();
            return(await tcs.Task.ConfigureAwait(false));
        }
Exemple #28
0
    public async Task BasicTest()
    {
        if (TestRunnerInfo.IsBuildAgent())
        {
            return; // No Redis on build agent for now
        }
        var db       = GetRedisDb();
        var started  = TaskSource.New <Unit>(true);
        var streamer = db.GetStreamer <int>("s");
        await streamer.Remove();

        var streamerCopy = db.GetStreamer <int>("s");

        var writeTask = streamer.Write(
            Delays(new[] { 0.1, 0.2, 0.3, 0.1 }),
            _ => started.SetResult(default));
Exemple #29
0
        /// <summary>
        /// Runs a sequence of Actions so that it can be awaited.
        /// </summary>
        /// <param name="actions">An array of FiniteTimeAction objects.</param>
        public Task <ActionState> RunActionsAsync(params FiniteTimeAction[] actions)
        {
            if (actions.Length == 0)
            {
                return(Task.FromResult <ActionState>(null));
            }

            var tcs = new TaskCompletionSource <ActionState>();

            FiniteTimeAction completion = new TaskSource(tcs);
            var asyncAction             = actions.Length > 0 ? new Sequence(actions, completion)
            {
                CancelAction = s => tcs.TrySetCanceled()
            } : completion;

            Application.Current.ActionManager.AddAction(asyncAction, this);
            return(tcs.Task);
        }
Exemple #30
0
    public static Disposable <Task, CancellationTokenRegistration> ToTask(
        this CancellationToken token,
        Exception exceptionWhenCancelled,
        TaskCreationOptions taskCreationOptions = default)
    {
        // ReSharper disable once HeapView.PossibleBoxingAllocation
        var ts = TaskSource.New <Unit>(exceptionWhenCancelled, taskCreationOptions);
        var r  = token.Register(arg => {
            var ts1 = TaskSource.For((Task <Unit>)arg !);
            ts1.SetException((Exception)ts1.Task.AsyncState !);
        }, ts.Task);

#if NETSTANDARD
        return(Disposable.New((Task)ts.Task, r, (_, r1) => r1.Dispose()));
#else
        return(Disposable.New((Task)ts.Task, r, (_, r1) => r1.Unregister()));
#endif
    }
Exemple #31
0
    protected virtual async Task Run(TimeSpan duration, CancellationToken cancellationToken)
    {
        Counters.Clear();
        var startTaskSource = TaskSource.New <Unit>(true);
        var tasks           = Enumerable.Range(0, ConcurrencyLevel)
                              .Select(async i => {
            await startTaskSource.Task.ConfigureAwait(false);
            return(await Benchmark(i, duration, cancellationToken).ConfigureAwait(false));
        })
                              .ToArray();
        await Task.Delay(100, cancellationToken).ConfigureAwait(false); // Wait to make sure all the tasks are created & scheduled

        if (ForceGCCollect)
        {
            GC.Collect();
        }

        Stopwatch = Stopwatch.StartNew();
        startTaskSource.SetResult(default);
Exemple #32
0
        /// <summary>
        /// Find the Task from the Windows Task Scheduler
        /// </summary>
        public Task FindTask()
        {
            Task result = Report.TaskFolder.GetTasks().FirstOrDefault(i => i.Definition.RegistrationInfo.Source == TaskSource);

            foreach (var task in Report.TaskFolder.GetTasks())
            {
                if (task.Definition.RegistrationInfo.Source.ToLower().Trim() == TaskSource.ToLower().Trim())
                {
                    result = task;
                }
            }

            if (result == null)
            {
                //check if the task is still existing (typically if the report was moved or renamed)
                foreach (Task task in Report.TaskFolder.GetTasks().Where(i => i.Name.EndsWith(GUID) && i.Definition.RegistrationInfo.Source.EndsWith(GUID)))
                {
                    bool   ok         = true;
                    string reportPath = GetTaskSourceDetail(task.Definition.RegistrationInfo.Source, 0);
                    if (File.Exists(reportPath))
                    {
                        try
                        {
                            //probably a report copy, the task should stay attached on the initial report
                            Report report = Report.LoadFromFile(reportPath, Report.Repository);
                            if (report.GUID == GetTaskSourceDetail(task.Definition.RegistrationInfo.Source, 1) && report.Schedules.Exists(i => i.GUID == GUID))
                            {
                                ok = false;
                            }
                        }
                        catch { }
                    }
                    if (ok)
                    {
                        //take this task
                        result = task;
                        break;
                    }
                }
            }

            return(result);
        }
 public PublicationState(IPublication <T> publication, IComputed <T> computed, Moment createdAt, bool isDisposed,
                         TaskSource <Unit> whenInvalidatedSource = default,
                         TaskSource <Unit> whenOutdatedSource    = default)
 {
     if (whenInvalidatedSource.IsEmpty)
     {
         whenInvalidatedSource = TaskSource.New <Unit>(true);
     }
     if (whenOutdatedSource.IsEmpty)
     {
         whenOutdatedSource = TaskSource.New <Unit>(true);
     }
     Publication           = publication;
     CreatedAt             = createdAt;
     IsDisposed            = isDisposed;
     WhenInvalidatedSource = whenInvalidatedSource;
     WhenOutdatedSource    = whenOutdatedSource;
     Computed              = computed;
     computed.Invalidated += _ => WhenInvalidatedSource.TrySetResult(default);
			public void Dispose()
			{	
				complete.WaitOne();
				task = null;
				start.Set();
				thread.Join();
			}
			void Process()
			{
				parent.Application.SetApplicationThreadInstance();

#if XBOX360
				thread.SetProcessorAffinity(new int[] { threadAffinity });
#else
				//match culture with the creation thread
				Thread.CurrentThread.CurrentCulture = culture;
#endif

				while (!temporary)
				{
					complete.Set();
					start.WaitOne();

					TaskSource task = this.task;

					if (task == null)
						break;

					this.task = null;

					complete.Reset();
					running.Set();

					IAction action = Interlocked.Exchange(ref task.action, null);

					if (action != null) // set action to null when a task in in flight
					{
						action.PerformAction(task.data);
						parent.ClearTask(task);
					}

					if (!temporary)
					{
						while (parent.RunQueueTask())
							continue;
					}
				}
				complete.Set();
			}
Exemple #36
0
 public Pipeline(TaskSource tasksSource, ExecTaskGenerator execTaskGenerator)
 {
     this.tasksSource = tasksSource;
     this.execTaskGenerator = execTaskGenerator;
 }
 protected override void Given()
 {
     customTasks = new CustomTasksDetector(taskFileFinder, null);
     taskFileFinder.FindFiles("basefolder").Returns(new List<string>());
 }
			public void Run(TaskSource task)
			{
				complete.WaitOne();

				this.task = task;

				start.Set();
				running.WaitOne();
			}