Пример #1
0
        // 1. Work item is added
        public void AddWork(WorkItem workItem)
        {
            // 2. Work task is decomposed
            List<Goal> newGoals = _decompService.Decompose(workItem);

            // 3. The goal's satisfied event is registered with this work enactor
            GoalSatisfiedHandler handler = null;
            handler = delegate(Goal g)
                {
                    GoalSatisified(g, workItem);
                    g.GoalSatisfied -= handler;
                };
            newGoals.ForEach(g => g.GoalSatisfied += handler);

            // 4. The goals are added to this enactor's list against the workitem
            //    and also the list of workitems being processed
            _workitemGoals.Add(workItem, newGoals);
            StartWork(workItem);

            // 5. Goals are registered with the world state service
            newGoals.ForEach(_goalService.RegisterGoal);

            // 6. Notify user of goals etc...
            foreach (var goal in newGoals)
            {
                _user.NotifyUser(workItem.taskName + " - " + goal.ToString());
            }
        }
Пример #2
0
 public WorkItemStatus Cancel(WorkItem item, bool allowAbort)
 {
     if (item == null)
         throw new ArgumentNullException("item");
     lock (_callbacks)
     {
         LinkedListNode<WorkItem> node = _callbacks.Find(item);
         if (node != null)
         {
             _callbacks.Remove(node);
             return WorkItemStatus.Queued;
         }
         else if (_threads.ContainsKey(item))
         {
             if (allowAbort)
             {
                 _threads[item].Abort();
                 _threads.Remove(item);
                 return WorkItemStatus.Aborted;
             }
             else
                 return WorkItemStatus.Executing;
         }
         else
             return WorkItemStatus.Completed;
     }
 }
        /// <summary>
        /// See <see cref="IModuleLoaderService.Load(WorkItem, IModuleInfo[])"/> for more information.
        /// </summary>
        public void Load(WorkItem workItem, params IModuleInfo[] modules)
        {
            Guard.ArgumentNotNull(workItem, "workItem");
            Guard.ArgumentNotNull(modules, "modules");

            InnerLoad(workItem, modules);
        }
                    private void EnqueueActiveFileItem(WorkItem item)
                    {
                        this.UpdateLastAccessTime();
                        var added = _workItemQueue.AddOrReplace(item);

                        Logger.Log(FunctionId.WorkCoordinator_ActiveFileEnqueue, s_enqueueLogger, Environment.TickCount, item.DocumentId, !added);
                        SolutionCrawlerLogger.LogActiveFileEnqueue(_processor._logAggregator);
                    }
                    private void CheckHigherPriorityDocument(WorkItem item)
                    {
                        if (!item.InvocationReasons.Contains(PredefinedInvocationReasons.HighPriority))
                        {
                            return;
                        }

                        AddHigherPriorityDocument(item.DocumentId);
                    }
Пример #6
0
 public static bool QueueUserWorkItem(WaitCallback callback,
                                         object state)
 {
     Contract.Requires(callback != null);
     Contract.Requires(threads != null);
     var item = new WorkItem(callback, state);
     workItemQueue.Enqueue(item);
     return true;
 }
Пример #7
0
 public void CompleteWork(WorkItem workItem)
 {
     if (/*_workAgent.started.Contains(workItem) &&*/ WorkAgent.processing.Contains(workItem))
     {
         _user.NotifyUser("Just completed workitem: " + workItem.taskName);
         WorkAgent.Complete(workItem, _workflow);
     }
     _completedGoals.Add(workItem, _workitemGoals[workItem]);
     _workitemGoals.Remove(workItem);
 }
Пример #8
0
 /// <summary>Initializes a new instance of the IOTaskScheduler class.</summary>
 public unsafe IOTaskScheduler()
 {
     // Configure the object pool of work items
     _availableWorkItems = new ObjectPool<WorkItem>(() =>
     {
         var wi = new WorkItem { _scheduler = this };
         wi._pNOlap = new Overlapped().UnsafePack(wi.Callback, null);
         return wi;
     }, new ConcurrentStack<WorkItem>());
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AuthorizationService"/> class.
 /// </summary>
 /// <param name="workItem">The work item.</param>
 public AuthorizationService([ServiceDependency]WorkItem workItem)
 {
     lock (syncObj) {
         this.workItem = workItem;
         authorizationStoreService = workItem.Services.Get<IAuthorizationStoreService>();
         if (authorizationStoreService != null) {
             authorizations = authorizationStoreService.GetAuthorizationsByUser(Thread.CurrentPrincipal.Identity.Name); // 获取当前用户的所有授权信息
         }
     }
 }
        /// <summary>
        /// See <see cref="IModuleLoaderService.Load(WorkItem, Assembly[])"/> for more information.
        /// </summary>
        public void Load(WorkItem workItem, params Assembly[] assemblies)
        {
            Guard.ArgumentNotNull(workItem, "workItem");
            Guard.ArgumentNotNull(assemblies, "assemblies");

            List<IModuleInfo> modules = new List<IModuleInfo>();

            foreach (Assembly assembly in assemblies)
                modules.Add(new ModuleInfo(assembly));

            InnerLoad(workItem, modules.ToArray());
        }
Пример #11
0
 public AuthenticationService([ServiceDependency]WorkItem workItem, [ServiceDependency] IUserSelectorService userSelector)
 {
     _userSelector = userSelector;
     if (workItem.RootWorkItem == null)
     {
         _rootWorkItem = workItem;
     }
     else
     {
         _rootWorkItem = workItem.RootWorkItem;
     }
 }
        public void QueueUserWorkItem(WaitCallback callback, object parameter)
        {
            var workItem = new WorkItem(callback, parameter);

            lock (_jobQueue)
            {
                _jobQueue.Enqueue(workItem);
                if (_threadsWaiting > 0)
                {
                    Monitor.Pulse(_jobQueue);
                }
            }
        }
                    public void Enqueue(WorkItem item)
                    {
                        this.UpdateLastAccessTime();

                        // Project work
                        item = item.With(documentId: null, projectId: item.ProjectId, asyncToken: this.Processor._listener.BeginAsyncOperation("WorkItem"));

                        var added = _workItemQueue.AddOrReplace(item);

                        Logger.Log(FunctionId.WorkCoordinator_Project_Enqueue, s_enqueueLogger, Environment.TickCount, item.ProjectId, !added);

                        SolutionCrawlerLogger.LogWorkItemEnqueue(this.Processor._logAggregator, item.ProjectId);
                    }
Пример #14
0
        public TimedWorker()
        {
            work = new WorkItem();
            workIsWaiting = new AutoResetEvent(false);
            workerIsStarting = new AutoResetEvent(false);
            workerIsDone = new AutoResetEvent(false);
            workIsDone = new AutoResetEvent(false);

            manager = new Thread(new ThreadStart(RunManager));
            worker = new Thread(new ThreadStart(RunWorker));
            manager.Start();
            worker.Start();
        }
 public override void Send(SendOrPostCallback d, object state)
 {
     if (Thread.CurrentThread == _uiThread)
     {
         d(state);
     }
     else
     {
         var workItem = new WorkItem { Callback = d, State = state, Handle = new AutoResetEvent(false) };
         _workItems.Add(workItem);
         workItem.Handle.WaitOne();
     }
 }
 public override void Send(SendOrPostCallback d, object state)
 {
     if (Thread.CurrentThread == uiThread)
     {
         d(state);
     }
     else
     {
         EnsureUIThread();
         var workItem = new WorkItem { callback = d, state = state, handle = new AutoResetEvent(false) };
         workItems.Add(workItem);
         workItem.handle.WaitOne();
     }
 }
                    public void Enqueue(WorkItem item)
                    {
                        Contract.ThrowIfFalse(item.DocumentId != null, "can only enqueue a document work item");

                        this.UpdateLastAccessTime();

                        var added = _workItemQueue.AddOrReplace(item);

                        Logger.Log(FunctionId.WorkCoordinator_DocumentWorker_Enqueue, s_enqueueLogger, Environment.TickCount, item.DocumentId, !added);

                        CheckHigherPriorityDocument(item);

                        SolutionCrawlerLogger.LogWorkItemEnqueue(
                            this.Processor._logAggregator, item.Language, item.DocumentId, item.InvocationReasons, item.IsLowPriority, item.ActiveMember, added);
                    }
Пример #18
0
        public LiveUpgradeService([ServiceDependency]WorkItem workItem, [ServiceDependency]IPropertyService propertyService)
        {
            this.workItem = workItem;
            this.propertyService = propertyService;

            LiveUpgradeConfigurationSection cs = ConfigurationManager.GetSection(LIVEUPGRADE_SECTION) as LiveUpgradeConfigurationSection;
            UpgradeSetting setting = GetSetting();
            if (cs != null && setting != null)
            {
                detecter = new UpgradeDetecter(this);
                if (setting.CheckInterval > 0) {
                    detecter.CheckInterval = setting.CheckInterval;
                    detecter.Start();
                }
            }
        }
Пример #19
0
		public static bool QueueUserWorkItem(WaitCallback callback, object state)
		{
			if (callback == null)
			{
				throw new ArgumentNullException("callback");
			}

			WorkItem workItem = new WorkItem()
			{
				Callback = callback,
				State = state,
				Context = ExecutionContext.Capture()
			};

			bool success = false;

			// Start tracking this work item
			lock (_WorkItems)
			{
				_WorkItems.Add(workItem);
			}

			try
			{
				// Place work item on the thread pool queue
				success = ThreadPool.QueueUserWorkItem(new WaitCallback(HandleCallback), workItem);
			}
			catch
			{
				// Work item could not be queued
				success = false;
				throw;
			}
			finally
			{
				if (!success)
				{
					// Stop tracking this work item
					RemoveWorkItem(workItem);
				}
			}

			return success;
		}
Пример #20
0
        /// <summary>
        /// Adds items to the work queue.
        /// 
        /// If the unique for the item already exists, then the work item is discarded.
        /// 
        /// If the priority is greater than previous items in the queue, then the new work item is
        /// inserted prior to the other items.
        /// 
        /// This code maintains the sorted order of the workitems.
        /// </summary>
        /// <param name="oNewItem"></param>
        public void AddPrioritised(WorkItem oNewItem)
        {
            lock(m_Lock_WorkItem_AddRemove)
            {
                foreach (WorkItem oItem in m_WorkItems)
                    if (oItem.Key.ToString() == oNewItem.Key.ToString())
                    {
                        Debug.WriteLine("PrioritisedArrayList: Key Already Queued: Skipped Request");
                        return;
                    }

                m_MREs.Add(oNewItem.MRE);

                int i = m_WorkItems.BinarySearch(oNewItem);

                if (i < 0)
                    m_WorkItems.Insert(~i, oNewItem);
                else
                    m_WorkItems.Insert(i, oNewItem);
            }
        }
                    public void Enqueue(WorkItem item)
                    {
                        Contract.ThrowIfFalse(item.DocumentId != null, "can only enqueue a document work item");

                        // we only put workitem in high priority queue if there is a text change.
                        // this is to prevent things like opening a file, changing in other files keep enqueuing
                        // expensive high priority work.
                        if (!item.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged))
                        {
                            return;
                        }

                        // check whether given item is for active document, otherwise, nothing to do here
                        if (_processor._documentTracker == null ||
                            _processor._documentTracker.GetActiveDocument() != item.DocumentId)
                        {
                            return;
                        }

                        // we need to clone due to waiter
                        EnqueueActiveFileItem(item.With(Listener.BeginAsyncOperation("ActiveFile")));
                    }
Пример #22
0
 public void Request(string cmd, int id, int credits)
 {
     switch (cmd)
     {
         case "Setup":
         case "Work":
             lock (requestsLock)
             {
                 Thread req = new Thread(Req);
                 WorkItem w = new WorkItem(req, cmd, credits);
                 requests.Add(id, w);
                 req.Start(new IComparable[] { cmd, id, credits });
             }
             break;
         case "Cancel":
             lock (requestsLock)
             {
                 if (requests.ContainsKey(id))
                     new Thread(Cancel).Start(id);
             }
             break;
         default: throw new Exception("Unknown command: " + cmd);
     }
 }
Пример #23
0
 private static IndexEntry ReadNextNoSeek(WorkItem workItem)
 {
     //workItem.Stream.Read(workItem.Buffer, 0, IndexEntrySize);
     //var entry = (IndexEntry)Marshal.PtrToStructure(workItem.BufferHandle.AddrOfPinnedObject(), typeof(IndexEntry));
     //return entry;
     return new IndexEntry(workItem.Reader.ReadUInt64(), workItem.Reader.ReadInt64());
 }
Пример #24
0
 private static IndexEntry ReadEntry(int indexNum, WorkItem workItem)
 {
     workItem.Stream.Seek(IndexEntrySize*(long)indexNum + PTableHeader.Size, SeekOrigin.Begin);
     return ReadNextNoSeek(workItem);
 }
Пример #25
0
 private static void PositionAtEntry(int indexNum, WorkItem workItem)
 {
     workItem.Stream.Seek(IndexEntrySize * (long)indexNum + PTableHeader.Size, SeekOrigin.Begin);
 }
                    private async Task ProcessDocumentAsync(Solution solution, ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source)
                    {
                        if (this.CancellationToken.IsCancellationRequested)
                        {
                            return;
                        }

                        var processedEverything = false;
                        var documentId = workItem.DocumentId;

                        try
                        {
                            using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessDocumentAsync, source.Token))
                            {
                                var cancellationToken = source.Token;
                                var document = solution.GetDocument(documentId);
                                if (document != null)
                                {
                                    await ProcessDocumentAnalyzersAsync(document, analyzers, workItem, cancellationToken).ConfigureAwait(false);
                                }

                                if (!cancellationToken.IsCancellationRequested)
                                {
                                    processedEverything = true;
                                }
                            }
                        }
                        catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
                        {
                            throw ExceptionUtilities.Unreachable;
                        }
                        finally
                        {
                            // we got cancelled in the middle of processing the document.
                            // let's make sure newly enqueued work item has all the flag needed.
                            if (!processedEverything)
                            {
                                _workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem")));
                            }

                            SolutionCrawlerLogger.LogProcessActiveFileDocument(_processor._logAggregator, documentId.Id, processedEverything);

                            // remove one that is finished running
                            _workItemQueue.RemoveCancellationSource(workItem.DocumentId);
                        }
                    }
Пример #27
0
            private void EnsureModuleClassesExist(WorkItem workItem)
            {
                if (moduleClasses.Count == moduleTypes.Count)
                    return;

                try
                {
                    foreach (Type moduleType in moduleTypes)
                    {
                        IModule module = (IModule)workItem.Items.AddNew(moduleType);
                        moduleClasses.Add(module);

                        if (traceSource != null)
                            traceSource.TraceInformation(Properties.Resources.LogModuleAdded, moduleType);
                    }
                }
                catch (FileNotFoundException ex) { ThrowModuleReferenceException(ex); }
                catch (Exception ex) { ThrowModuleLoadException(ex); }
            }
Пример #28
0
 private void ReturnWorkItem(WorkItem workItem)
 {
     _workItems.Return(workItem);
 }
Пример #29
0
            public void LoadServices(WorkItem workItem)
            {
                if (loadedServices)
                    return;

                loadedServices = true;
                EnsureModuleClassesExist(workItem);

                try
                {
                    foreach (IModule moduleClass in moduleClasses)
                    {
                        moduleClass.AddServices();

                        if (traceSource != null)
                            traceSource.TraceInformation(Properties.Resources.AddServicesCalled, moduleClass.GetType());
                    }

                    foreach (ServiceMetadata svc in services)
                    {
                        if (svc.AddOnDemand)
                        {
                            workItem.Services.AddOnDemand(svc.InstanceType, svc.RegistrationType);

                            if (traceSource != null)
                                traceSource.TraceInformation(Properties.Resources.ServiceAddedOnDemand, Name, svc.InstanceType);
                        }
                        else
                        {
                            workItem.Services.AddNew(svc.InstanceType, svc.RegistrationType);

                            if (traceSource != null)
                                traceSource.TraceInformation(Properties.Resources.ServiceAdded, Name, svc.InstanceType);
                        }
                    }
                }
                catch (Exception ex) { ThrowModuleLoadException(ex); }
            }
                    private bool GetNextWorkItem(out WorkItem workItem, out CancellationTokenSource documentCancellation)
                    {
                        // GetNextWorkItem since it can't fail. we still return bool to confirm that this never fail.
                        var documentId = _processor._documentTracker.GetActiveDocument();
                        if (documentId != null)
                        {
                            if (_workItemQueue.TryTake(documentId, out workItem, out documentCancellation))
                            {
                                return true;
                            }
                        }

                        return _workItemQueue.TryTakeAnyWork(
                            preferableProjectId: null,
                            dependencyGraph: _processor.DependencyGraph,
                            analyzerService: _processor.DiagnosticAnalyzerService,
                            workItem: out workItem,
                            source: out documentCancellation);
                    }