internal void CompleteWithResult (ITaskResult result) {
            if (CheckForDiscardedError())
                return;

            if (result != null)
                _Future.Complete(result.Value);
            else
                _Future.Complete(null);

            Dispose();
        }
示例#2
0
 public void AfterTaskExecute(Identity id, ITask<object> task, TaskContext context, ITaskResult<object> result)
 {
     try
     {
         foreach (ITaskInterceptor nestedInterceptor in _nestedInterceptors)
         {
             nestedInterceptor.AfterTaskExecute(id, task, context, result);
         }
     }
     catch (Exception ex)
     {
         context.Log.Error(ex.Message);
     }
 }
示例#3
0
 public void AfterTaskExecute(Identity id, ITask<object> task, TaskContext context, ITaskResult<object> result)
 {
     if (result.IsSuccess)
     {
         object data = result.Data;
         if (data == null || data is Nothing)
         {
             context.Log.Info("Completed");
         }
         else
         {
             context.Log.Info("Completed. Result is {0}", FormatData(data));
         }
     }
     else
     {
         context.Log.Error(result.Error == null ? "Unknown error occured" : result.Error.Message);
     }
 }
示例#4
0
        private string GetToken(ITask task)
        {
            string      tokenId = string.Empty;
            ITaskResult result  = task.GetResult();

            if (result != null)
            {
                List <string> logs = result.GetLog();
                for (int i = 0; i < logs.Count; i++)
                {
                    if (logs[i].Contains(TokenPattern))
                    {
                        tokenId = logs[i].Substring(logs[i].IndexOf(TokenPattern) + 7);
                        break;
                    }
                    if (i == 200)
                    {
                        break;
                    }
                }
            }
            return(tokenId);
        }
示例#5
0
        public bool WaitForStartupMessage(ITask task)
        {
            bool        Found  = false;
            ITaskResult result = task.GetResult();

            if (result != null)
            {
                List <string> logs = result.GetLog();
                for (int i = 0; i < logs.Count; i++)
                {
                    if (logs[i].Contains("CTRL+C to quit"))
                    {
                        Found = true;
                        break;
                    }
                    if (i == 200)
                    {
                        break;
                    }
                }
            }
            return(Found);
        }
示例#6
0
文件: Job.cs 项目: wuhaiying83/EMR
        private void StartThread()
        {
            DateTime       dtJobStartTime = DateTime.Now;
            TaskResultList objTaskResults = new TaskResultList();

            Status = JobStatusType.Running;
            OnJobBegin();

            JobResultType enuJobResult = JobResultType.Completed;

            int  intTaskIndex        = 0;
            int  intTaskCount        = _objTasks.Count;
            bool blnHasBeenCancelled = false;

            while (intTaskIndex < intTaskCount)
            {
                ITask objTask = _objTasks[intTaskIndex];

                blnHasBeenCancelled = HasBeenCancelled();
                if (blnHasBeenCancelled == true)
                {
                    enuJobResult = JobResultType.Cancelled;
                    break;
                }

                DateTime    dtTaskStartTime = DateTime.Now;
                JobTicket   objJobTicket    = new JobTicket(dtTaskStartTime, HasBeenCancelled, TaskProgressChanged);
                ITaskResult objTaskResult   = null;

                try
                {
                    OnTaskBegin(objTask, intTaskIndex, intTaskCount);
                    objTaskResult = objTask.Execute(objJobTicket);
                }
                catch (Exception objException)
                {
                    string    strErrorMessage = objException.ToString();
                    TaskStats objTaskStats    = new TaskStats(objTask, dtTaskStartTime, DateTime.Now);
                    objTaskResult = new TaskResult(objTask, objTaskStats, TaskResultType.Failed, strErrorMessage);
                }

                if (objTaskResult == null)
                {
                    string    strErrorMessage = "A null value was returned by the task.";
                    TaskStats objTaskStats    = new TaskStats(objTask, dtTaskStartTime, DateTime.Now);
                    objTaskResult = new TaskResult(objTask, objTaskStats, TaskResultType.Failed, strErrorMessage);
                }

                blnHasBeenCancelled = HasBeenCancelled();
                if (blnHasBeenCancelled == true)
                {
                    objTaskResults.Add(objTaskResult);
                    break;
                }
                else
                {
                    TaskActionType enuTaskActionType = OnTaskEnd(objTaskResult, intTaskIndex);
                    if (enuTaskActionType == TaskActionType.Retry)
                    {
                        continue;
                    }
                    else if (enuTaskActionType == TaskActionType.Continue)
                    {
                        objTaskResults.Add(objTaskResult);
                        intTaskIndex++;

                        if (objTaskResult.Result == TaskResultType.RebootRequired)
                        {
                            enuJobResult = JobResultType.RebootRequired;
                            break;
                        }

                        continue;
                    }
                    else if (enuTaskActionType == TaskActionType.Cancel)
                    {
                        objTaskResults.Add(objTaskResult);
                        enuJobResult = JobResultType.Cancelled;
                        break;
                    }
                }
            }

            if (blnHasBeenCancelled == true)
            {
                for (int intRemainingTaskIndex = intTaskIndex + 1; intRemainingTaskIndex < intTaskCount; intRemainingTaskIndex++)
                {
                    ITask       objRemainingTask       = _objTasks[intRemainingTaskIndex];
                    TaskStats   objTaskStats           = new TaskStats(objRemainingTask, dtJobStartTime, DateTime.Now);
                    ITaskResult objRemainingTaskResult = new TaskResult(objRemainingTask, objTaskStats, TaskResultType.Cancelled);

                    objTaskResults.Add(objRemainingTaskResult);
                }
            }

            Thread.Sleep(200);

            JobResult objJobResult = new JobResult(this, enuJobResult, dtJobStartTime, DateTime.Now, new TaskResultList(objTaskResults));

            OnJobEnd(objJobResult);

            Thread.Sleep(200);

            Status = JobStatusType.Completed;
        }
示例#7
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="TaskResultUpdateException" /> class.
 /// </summary>
 /// <param name="result">The result.</param>
 /// <param name="message">The message.</param>
 /// <param name="innerException">The inner exception.</param>
 public TaskResultUpdateException(ITaskResult result, string message, Exception innerException)
     : base(message, innerException)
 {
     Result = result;
 }
示例#8
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="TaskResultUpdateException" /> class.
 /// </summary>
 /// <param name="result">The result.</param>
 /// <param name="message">The message.</param>
 public TaskResultUpdateException(ITaskResult result, string message)
     : base(message)
 {
     Result = result;
 }
示例#9
0
 protected override ITaskResult ProcessTaskResult(ITaskResult result)
 {
     return(result);
 }
示例#10
0
 protected abstract ITaskResult ProcessTaskResult(ITaskResult result);
        /// <summary>
        /// Adds the task result.	
        /// </summary>
        /// <param name="result">The result.</param>
        /// <remarks></remarks>
        public void AddTaskResult(ITaskResult result)
        {
            taskResults.Add(result);
            if (Failed || Status == IntegrationStatus.Exception)
                return;

            Status = result.CheckIfSuccess() ? IntegrationStatus.Success : IntegrationStatus.Failure;
        }
示例#12
0
        public async Task WriteResultAsync(ServiceId serviceId, MethodId methodId, string intentId, ITaskResult result)
        {
            var fileName = GetResultFileName(serviceId, methodId, intentId);
            var filePath = Path.Combine(_resultsDirectory, fileName);

            var serializedResult = _serializer.SerializeToBytes(result);

            EnsureDirectoryExists(_resultsDirectory);
            using (var fileStream = new FileStream(
                       filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read,
                       FileBufferSize, FileOptions.Asynchronous | FileOptions.WriteThrough))
            {
                await fileStream.WriteAsync(serializedResult, 0, serializedResult.Length);

                fileStream.SetLength(fileStream.Position);
            }
        }
示例#13
0
 /// <summary>
 /// When TRUE, the routine execution has succeeded, and optionally
 /// has a <see cref="ITaskResult.Value"/> if the routine method returns generic
 /// <see cref="Task{TResult}"/>. This flag is mutually exclusive with
 /// <see cref="IsFaulted"/> and <see cref="ITaskResult.IsCanceled"/>.
 /// </summary>
 public static bool IsSucceeded(this ITaskResult taskResult) => !taskResult.IsCanceled && !taskResult.IsFaulted();
示例#14
0
 /// <summary>
 /// When TRUE, the routine has failed with an error described in the
 /// <see cref="Exception"/> property. This flag is mutually exclusive
 /// with <see cref="ITaskResult.IsCanceled"/> and <see cref="IsSucceeded"/>.
 /// </summary>
 public static bool IsFaulted(this ITaskResult taskResult) => taskResult.Exception != null;
示例#15
0
 public void AddTaskResult(ITaskResult result)
 {
     taskResults.Add(result);
     if (! (Failed || Status == IntegrationStatus.Exception)) Status = result.Succeeded() ? IntegrationStatus.Success : IntegrationStatus.Failure;
 }
        public void OnRoutineCompleted(ServiceId serviceId, MethodId methodId, string intentId, ITaskResult taskResult)
        {
            List <TrackedInvocation> listeners = null;

            lock (_trackedInvocations)
            {
                for (var node = _trackedInvocations.First; node != null;)
                {
                    var nextNode = node.Next;

                    var trackedInvocation = node.Value;
                    if (trackedInvocation.IntentId == intentId &&
                        trackedInvocation.ServiceId == serviceId &&
                        trackedInvocation.MethodId == methodId)
                    {
                        StopTracking(node);

                        if (listeners == null)
                        {
                            listeners = new List <TrackedInvocation>(capacity: 2);
                        }
                        listeners.Add(trackedInvocation);
                    }

                    node = nextNode;
                }
            }

            if (listeners == null)
            {
                return;
            }

            foreach (var trackedInvocation in listeners)
            {
                if (trackedInvocation.CancellationToken.IsCancellationRequested)
                {
                    continue;
                }
                var sink = trackedInvocation.CompletionSink;
                Task.Run(() => sink.TrySetResult(taskResult));
            }
        }
示例#17
0
        public void Start()
        {
            TimeSpan waitTime = new TimeSpan(0);
            int      brakTime = 5;
            int      stepTime = 1;
            int      stopTime = 5;

            message = new TaskMessage();
            started = true;

            try
            {
                do
                {
                    OnClientUpdate(new ClientUpdateEventArgs("Wysyłanie wiadomości..."));
                    bytes = TaskMessage.Serialize(message);
                    client.Send(bytes, bytes.Length, _host, _port);

                    //Odbierz wiadomość
                    received = false;
                    OnClientUpdate(new ClientUpdateEventArgs("Czekam na odpowiedź..."));

                    IAsyncResult iresult = client.BeginReceive(new AsyncCallback(ReceiveCallback), null);
                    int          index   = WaitHandle.WaitAny(new WaitHandle[] { iresult.AsyncWaitHandle }, timeout, false);

                    if (index == WaitHandle.WaitTimeout)
                    {
                        OnClientUpdate(new ClientUpdateEventArgs("Serwer nie odpowiada, czekam " + stopTime + "s..."));
                        if (stopTime < 60)
                        {
                            stopTime += stepTime;
                        }
                        waitTime = new TimeSpan(0, 0, stopTime);
                        Thread.Sleep(waitTime);
                        //break;
                    }
                    else
                    {
                        stopTime = 5;
                        //Trzeba chwilę poczekać...
                        OnClientUpdate(new ClientUpdateEventArgs("Kończę odbieranie wiadomości..."));

                        DateTime startTime = DateTime.Now;
                        waitTime = new TimeSpan(0, 0, 1);  //1s
                        while (!received && DateTime.Now - startTime < waitTime)
                        {
                            continue;
                        }

                        if (!received)
                        {
                            OnClientUpdate(new ClientUpdateEventArgs("Nie udało się odebrać wiadomości :("));
                            break;
                        }

                        OnClientUpdate(new ClientUpdateEventArgs("Wiadomość odebrana"));

                        if (message.TaskId < 0)
                        {
                            if (brakTime < 60)
                            {
                                brakTime += stepTime;
                            }
                            OnClientUpdate(new ClientUpdateEventArgs("Chwilowo brak aktywnych zadań, czekam " + brakTime.ToString() + "s..."));
                            waitTime = new TimeSpan(0, 0, brakTime);
                            Thread.Sleep(waitTime);
                        }
                        else
                        if (message.Task != null)
                        {
                            brakTime = 5;
                            _task    = message.Task;
                            _id      = message.TaskId;
                            OnClientUpdate(new ClientUpdateEventArgs("Wykonuję zadanie..."));

                            ITaskResult result = _task.Execute();
                            message.Result = result;

                            OnClientUpdate(
                                new ClientUpdateEventArgs("Zakończyłem szukanie")
                                );
                        }
                    }
                } while (started);
            }
            catch (SocketException)
            {
                OnClientUpdate(new ClientUpdateEventArgs("Serwer nie odpowiada"));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Błąd aplikacji klienta: " + ex.ToString());
            }
            finally
            {
                started = false;
            }
        }
示例#18
0
 public ImmediatePromise(PromiseFactory promiseFactory, ITaskFactory factory, ITaskResult task) : base(promiseFactory, factory, task)
 {
 }
示例#19
0
        public Task WriteResultAsync(ServiceId serviceId, MethodId methodId, string intentId, ITaskResult result)
        {
            var serializedTaskResult = _serializer.SerializeToString(result);

            var expectedETag = (methodId as PersistedMethodId)?.ETag;

            lock (_entryMap)
            {
                if (!_entryMap.TryGetValue(intentId, out var entry))
                {
                    entry = new StorageEntry();
                    _entryMap.Add(intentId, entry);
                }
                else if (!string.IsNullOrEmpty(expectedETag) && entry.ETag != expectedETag)
                {
                    throw new ETagMismatchException(expectedETag, entry.ETag);
                }

                entry["ServiceId"] = serviceId.Clone();
                entry["MethodId"]  = methodId.Clone();
                entry["Result"]    = serializedTaskResult;
                entry.ETag         = DateTimeOffset.UtcNow.Ticks.ToString();
            }

            return(Task.CompletedTask);
        }
示例#20
0
 protected override ITaskResult ProcessTaskResult(ITaskResult result)
 {
     return(result.Immediately);
 }
示例#21
0
        public async Task WriteResultAsync(ServiceId serviceId, MethodId methodId, string intentId, ITaskResult result)
        {
            var tableName = GetTableQualifiedName(serviceId, methodId);

            var key = new StorageRecord
            {
                service   = serviceId.Name,
                method    = methodId.Name,
                intent_id = intentId
            };

            var record = new StorageRecord
            {
                etag        = DateTimeOffset.UtcNow.Ticks,
                status      = (int)Statuses.Complete,
                outcome     = (int)(result.IsCanceled ? Outcomes.Canceled : (result.IsFaulted() ? Outcomes.Failed : Outcomes.Succeeded)),
                updated_at  = DateTimeOffset.Now,
                format      = _serializer.Format,
                task_result = _serializer.SerializeToBytes(result)
            };

            var query = new StringBuilder("UPDATE ").Append(tableName);

            if (_settings.ResultTTL.HasValue)
            {
                query.Append(" USING TTL ").Append((int)_settings.ResultTTL.Value.TotalSeconds);
            }

            query.Append(" SET ");
            WriteValues(query, record, delimiter: ", ");
            query.Append(", execution_state = null, method_state = null, flow_context = null, continuation = null, continuation_state = null");
            query.Append(" WHERE ");
            WriteValues(query, key, delimiter: " AND ");

            await ExecuteQueryAsync(serviceId, methodId, query.ToString());
        }
 public void AddTaskResult(ITaskResult result)
 {
     throw new NotImplementedException();
 }
示例#23
0
 public NormalPromise(PromiseFactory promiseFactory, ITaskFactory factory, ITaskResult task) : base(promiseFactory, factory, task)
 {
 }
示例#24
0
        internal void CompleteWithResult(ITaskResult result)
        {
            if (CheckForDiscardedError())
                return;

            if (_Future == null) {
                if (result == null) {
                    // Disposed without result
                    return;
                } else {
                    // FIXME: is this right?
                    // Disposed with result but nowhere to send it.
                    return;
                }
            } else if (result != null) {
                _Future.Complete(result.Value);
            } else {
                _Future.Complete(null);
            }

            Dispose();
        }
示例#25
0
 private IPromise <T> CreatePromise <T>(ITaskResult result)
 {
     return(new NormalPromise <T>(Factory, TaskFactory, result));
 }
示例#26
0
 public void AddTaskResult(ITaskResult result)
 {
     throw new NotImplementedException();
 }
示例#27
0
 public PriorityPromise(PromiseFactory promiseFactory, ITaskFactory factory, ITaskResult task, PromisePriority priority) : base(promiseFactory, factory, task)
 {
     this._priority = priority;
 }