Ejemplo n.º 1
0
        //public static void UpdateTaskState(TaskCache cache)
        public void UpdateStateAsync()
        {
            //var cache = GetById(taskId);

            // todo : PFX.Task.Run in .Net 4.5
            PFX.Task.Factory.StartNew(() =>
            {
                if (!this._isUpdating && (this._lastUpdateTime + UPDATE_INTERVAL < DateTime.Now || DateTime.Now < this._lastUpdateTime))
                {
                    bool wasFinished          = false;
                    bool isThisThreadUpdating = false;
                    lock (this.StateLock)
                    {
                        if (!this._isUpdating && (this._lastUpdateTime + UPDATE_INTERVAL < DateTime.Now || DateTime.Now < this._lastUpdateTime))
                        {
                            this._isUpdating     = true;
                            isThisThreadUpdating = true;

                            wasFinished = this.StateInfo.IsFinished();
                        }
                    }

                    if (isThisThreadUpdating)
                    {
                        try
                        {
                            if (!wasFinished)
                            {
                                var timer = System.Diagnostics.Stopwatch.StartNew();

                                var newState = this.Context.Controller.GetTaskStateInfo(this.Context);

                                timer.Stop();
                                if (timer.Elapsed > UPDATE_DURATION_TO_WARN)
                                {
                                    Log.Warn(String.Format("Task {0} update took {1} seconds", this.Context.TaskId, timer.Elapsed.TotalSeconds)); // Context.TaskId is immutable
                                }
                                SetState(newState);
                                if (gcCollector != null)
                                {
                                    gcCollector.push(this.Context, this.Context.TaskId, newState);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            SetState(TaskState.Failed, e.Message);                                                 // todo : retries

                            Log.Error(String.Format("Exception on update task {0}: {1}", this.Context.TaskId, e)); // Context.TaskId is immutable
                            throw;
                        }
                        finally
                        {
                            lock (this.StateLock)
                            {
                                this._lastUpdateTime = DateTime.Now;
                                this._isUpdating     = false;
                            }
                        }
                    }
                }
            });
        }