Example #1
0
        public void Send(ASdu aSdu)
        {
            acknowledgedReceiveSequenceNumber = receiveSequenceNumber;
            var requestAPdu = new APdu(sendSequenceNumber, receiveSequenceNumber, APdu.ApciType.I_FORMAT, aSdu);

            sendSequenceNumber = (sendSequenceNumber + 1) % 32768;

            if (maxTimeNoAckSentFuture != null)
            {
                maxTimeNoAckSentFuture.Cancel();
                maxTimeNoAckSentFuture = null;
            }

            if (maxTimeNoAckReceivedFuture == null)
            {
                ScheduleMaxTimeNoAckReceivedFuture();
            }

            var length = requestAPdu.Encode(buffer, settings);

            writer.Write(buffer, 0, length);
            writer.Flush();

            ResetMaxIdleTimeTimer();
        }
Example #2
0
        private void HandleReceiveSequenceNumber(APdu aPdu)
        {
            if (acknowledgedSendSequenceNumber != aPdu.GetReceiveSeqNumber())
            {
                if (GetSequenceNumberDifference(aPdu.GetReceiveSeqNumber(), acknowledgedSendSequenceNumber) >
                    GetNumUnconfirmedIPdusSent())
                {
                    throw new IOException("Got unexpected receive sequence number: " + aPdu.GetReceiveSeqNumber()
                                          + ", expected a number between: " + acknowledgedSendSequenceNumber + " and "
                                          + sendSequenceNumber);
                }

                if (maxTimeNoAckReceivedFuture != null)
                {
                    maxTimeNoAckReceivedFuture.Cancel();
                    maxTimeNoAckReceivedFuture = null;
                }

                acknowledgedSendSequenceNumber = aPdu.GetReceiveSeqNumber();

                if (sendSequenceNumber != acknowledgedSendSequenceNumber)
                {
                    ScheduleMaxTimeNoAckReceivedFuture();
                }
            }
        }
Example #3
0
        public void Push(ActionRun <T> item)
        {
            ActionQueue.Enqueue(item);

            if (RunTask.Status == TaskStatus.Created)
            {
                RunTask.Start();
                RunTask.ContinueWith(task =>
                {
                    var ae = task.Exception;
                }, TaskContinuationOptions.OnlyOnFaulted);
            }
            else if (RunTask.Status == TaskStatus.RanToCompletion)
            {
                RunTask.Dispose();
                RunTask = Task.Factory.StartNew(Run);
            }
            else if (RunTask.Status == TaskStatus.Faulted)
            {
                CheckError();

                RunTask.Dispose();
                RunTask = Task.Factory.StartNew(Run);
            }
        }
Example #4
0
        private IEnumerable <Notification> When(RunTask message)
        {
            TaskRunId = message.TaskRunId;

            State = TaskState.CreatingTaskRun;

            yield return(new Notification(ActorTypes.TaskRun, TaskRunId.Value, new CreateTaskRun(TaskRunId.Value, Id, message.IsAbc)));
        }
        public async Task <ActionResult <RunTask> > PostRunTask([FromBody] RunTask runTask)
        {
            runTask.WhenCreated = DateTime.UtcNow;
            runTask.WhenChanged = DateTime.UtcNow;
            runTask.IsActive    = true;
            await service.Create(runTask);

            return(CreatedAtAction("GetRunTask", new { id = runTask.Id }, runTask));
        }
        /// <summary>
        ///  ジョブを実行<br />
        /// </summary>
        ///
        /// <returns>IEnumerator</returns>
        /// <param name="callback">コールバックハンドラ</param>
        /// <param name="request">リクエストパラメータ</param>
        public IEnumerator Run(
            Request.RunRequest request,
            UnityAction <AsyncResult <Result.RunResult> > callback
            )
        {
            var task = new RunTask(request, callback);

            return(Gs2RestSession.Execute(task));
        }
Example #7
0
        ClientData SwitchDo(GSSModel.Request.ClientData clientData)
        {//在创建工单的同时将逻辑数据提交到服务端处理
            TaskContainerLogicData tl = clientData.Data as TaskContainerLogicData;
            Tasks task = tl.WorkOrder;
            int   id   = dbhandle.AddTask(task);

            clientData.TaskID = id;
            string.Format("Sync create task and run :{0}", clientData.Data.GetType().Name);
            if (tl.LogicData.GetType().Name != typeof(RunTask).Name)
            {
                Unlock un   = tl.LogicData as Unlock;//bug 此处不能直接将object转换为json
                string json = un.MapObject <Unlock, UnlockLogic>().ConvertJson();
                // if(clientData.Data.GetType().Name==typeof())
                int code = dbhandle.InsertLogicJsonAfterTask(id, json);

                clientData.Data = null;
                if (code != StatueCode.Ok)
                {//未创建成功
                    clientData.Data    = code;
                    clientData.Message = "Error";
                }
                else
                {
                    string ret = WebServiceLib.URNolock((un.RoleId > 0 ? "2" : "1"), id.ToString());
                    clientData.Success = ret == "true";
                    string.Format("taskId=[{0}]->Unlock result:[{1}]", id, ret).Logger();
                    clientData.Message = ret;
                }
                return(clientData);
            }
            msgCommand cmd;
            RunTask    rt = tl.LogicData as RunTask;

            clientData.Data = null;
            string.Format("create work order and run-> {0}", rt.Command).Logger();
            string msg = string.Empty;

            cmd = (msgCommand)Enum.Parse(typeof(msgCommand), rt.Command);
            switch (cmd)
            {
            case msgCommand.GameNoticeStart:    //运行公告
                msg = WebServiceLib.GameNoticeStart(id.ToString());
                break;

            default:
                break;
            }
            clientData.Message = msg;
            if (!string.IsNullOrEmpty(msg))
            {
                clientData.Success = true;
            }
            return(clientData);
        }
Example #8
0
        public Task LoadFileSystemAsync(string title, Func <SwitchFs> fs, TitleSource source, bool blocking)
        {
            Task         task  = new Task(() => LoadFileSystem(fs, source));
            ProgressTask ptask = new RunTask(title, task)
            {
                Blocking = blocking
            };

            TaskManagerPage.Current.Queue.Submit(ptask);
            return(task);
        }
        public async Task <IActionResult> PutRunTask(int id, [FromBody] RunTask runTask)
        {
            if (id != runTask.Id)
            {
                return(BadRequest());
            }
            runTask.WhenChanged = DateTime.UtcNow;
            await service.Update(id, runTask);

            return(NoContent());
        }
        /// <summary>
        ///  ジョブを実行<br />
        /// </summary>
        ///
        /// <returns>IEnumerator</returns>
        /// <param name="callback">コールバックハンドラ</param>
        /// <param name="request">リクエストパラメータ</param>
        public IEnumerator Run(
            Request.RunRequest request,
            UnityAction <AsyncResult <Result.RunResult> > callback
            )
        {
            var task = new RunTask(request, callback);

            if (_certificateHandler != null)
            {
                task.UnityWebRequest.certificateHandler = _certificateHandler;
            }
            return(Gs2RestSession.Execute(task));
        }
        void WorkerDoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                lock (Running)
                {
                    while ((Running.Count < Concurrency) && (Current < Items.Count) && (!token.IsCancellationRequested))
                    {
                        var item    = Items[Current++];
                        var runTask = new RunTask {
                            Item = item, Name = GetName(item)
                        };
                        var progress = new Progress <ProgressReport>(tuple =>
                        {
                            runTask.Value   = tuple.Value;
                            runTask.Maximum = tuple.Maximum;
                            Event.Set();
                        });
                        runTask.Task = GetTask(item, progress, token.Token);
                        Running.Add(runTask);
                        var progressData = ProgressDatas.First(x => x.RunTask == null);
                        progressData.RunTask = runTask;
                        Event.Set();
                    }
                }
                if (Running.Count == 0)
                {
                    break;
                }

                var finished = Task.WhenAny(Running.Select(task => task.Task)).Result;
                lock (Running)
                {
                    var runTask = Running.First(tuple => tuple.Task == finished);
                    ProgressDatas.Single(x => x.RunTask == runTask).RunTask = null;
                    Running.Remove(runTask);
                    if (finished.Exception != null)
                    {
                        Exceptions.AddRange(finished.Exception.InnerExceptions);
                        Event.Set();
                    }
                    else if (finished.Status == TaskStatus.RanToCompletion)
                    {
                        Result[runTask.Item] = finished.Result;
                    }
                    ++Finished;
                    Event.Set();
                }
            }
        }
Example #12
0
        public void RunUntil(Func <bool> operation)
        {
            var task = new RunTask(operation, IntervalSpeed);

            var inactive = _tasks.Where(t => !t.Running).ToList();

            foreach (var t in inactive)
            {
                _tasks.Remove(t);
            }

            _tasks.Add(task);

            task.Start();
        }
Example #13
0
        public async Task StopAsync()
        {
            if (!Running)
            {
                return;
            }

            CancellationSource.Cancel();
            await RunTask;

            CancellationSource.Dispose();
            CancellationSource = null;
            RunTask.Dispose();
            RunTask = null;
        }
Example #14
0
        private void ScheduleMaxTimeNoTestConReceivedFuture()
        {
            if (maxTimeNoTestConReceivedFuture != null)
            {
                maxTimeNoTestConReceivedFuture.Cancel();
                maxTimeNoTestConReceivedFuture = null;
            }

            maxTimeNoTestConReceivedFuture = PeriodicTaskFactory.Start(() =>
            {
                Close();
                ConnectionClosed?.Invoke(new IOException(
                                             "The maximum time that no test frame confirmation was received (t1) has been exceeded. t1 = "
                                             + settings.MaxTimeNoAckReceived + "ms"));
            }, settings.MaxTimeNoAckReceived);
        }
        /// <summary>
        ///		Called to request that the task controller run a task.
        /// </summary>
        /// <param name="runTask">
        ///		The <see cref="RunTask"/> request message.
        /// </param>
        void OnRunTask(RunTask runTask)
        {
            if (runTask == null)
            {
                throw new ArgumentNullException("runTask");
            }

            Log.Information(
                "{ActorPath}: Received request to run task: {What} ({TotalTaskCount} tasks now active)",
                Self.Path.ToUserRelativePath(),
                runTask.What,
                ++_outstandingTaskCount
                );

            _taskRunnerRouter.Tell(
                new StartTask(runTask.What)
                );
        }
Example #16
0
        private void ResetMaxIdleTimeTimer()
        {
            if (maxIdleTimeTimerFuture != null)
            {
                maxIdleTimeTimerFuture.Cancel();
                maxIdleTimeTimerFuture = null;
            }

            maxIdleTimeTimerFuture = PeriodicTaskFactory.Start(() =>
            {
                try
                {
                    writer.Write(TestfrActBuffer, 0, TestfrActBuffer.Length);
                    writer.Flush();
                }
                catch (Exception)
                {
                    // ignored
                }
                ScheduleMaxTimeNoTestConReceivedFuture();
            }, settings.MaxIdleTime);
        }
        void SetupGrid()
        {
            var columns = Math.Max(1, Math.Min((int)Math.Ceiling(Math.Sqrt(Concurrency - 1)), 8));
            var rows    = (Concurrency + columns - 1) / columns + 1;

            for (var column = 0; column < columns; ++column)
            {
                progressGrid.ColumnDefinitions.Add(new ColumnDefinition());
            }

            for (var row = 0; row < rows; ++row)
            {
                progressGrid.RowDefinitions.Add(new RowDefinition());
            }

            OverallTask = new RunTask {
                Name = "Overall", Maximum = Items.Count
            };
            for (var ctr = 0; ctr < Concurrency; ++ctr)
            {
                AddProgress(ctr / columns + 1, ctr % columns);
            }
            AddProgress(0, 0, columns).RunTask = OverallTask;
        }
            //private static readonly object padlock = new object();
            //private RunTask() { }

            public int Sum(int lastnumber, string Cancel)
            {
                try
                {
                    List <Task> List = new List <Task>();
                    if (lastnumber > 0)
                    {
                        entity.LastNumber = lastnumber;
                        instance          = null;
                    }

                    if (instance == null)
                    {
                        CancellationTokenSource cancel = new CancellationTokenSource();
                        CancellationToken       cts;
                        instance = new RunTask();
                        var o     = new object();
                        var tag   = entity.LastNumber;
                        var count = 0;
                        var max   = int.MaxValue;

                        // var cancel = new CancellationTokenSource();
                        cts           = cancel.Token; //取消令牌
                        entity.Cts    = cts;
                        entity.Cancel = cancel;
                        //var List = new List<Task>();
                        for (int i = 0; i < 3; i++)
                        {
                            var t = Task.Run(() =>
                            {
                                var currentTag = 0; //值
                                while (tag < max)
                                {
                                    lock (o)
                                    {
                                        if (cts.IsCancellationRequested)
                                        {
                                            break;
                                        }
                                        /*(!token.IsCancellationRequested)*/

                                        // SpinWait.SpinUntil(() => Cancel == "取消");
                                        SpinWait.SpinUntil(() => false, 200); //延迟200ms
                                        tag       += 1;
                                        currentTag = tag;
                                        // Thread.Sleep(300);
                                        entity.Sum = currentTag;
                                        log.Info($"当前值{currentTag}");
                                        //Console.WriteLine($"当前值{currentTag}");
                                    }
                                }
                            }, cts);
                            List.Add(t);
                        }
                        entity.List = List;

                        #region 之前写法

                        //object o = new object();
                        ////var tag = 0;
                        //var tag = entity.tag = 0;
                        //var count = 0;
                        //var max = int.MaxValue;
                        //try
                        //{
                        //    var cancel = new CancellationTokenSource();
                        //    var token = cancel.Token;

                        //    var List = new List<Task>();
                        //    for (int i = 0; i < 3; i++)
                        //    {
                        //        var t = Task.Run(() =>
                        //        {
                        //            var currentTag = 0;//值
                        //            while (tag < max)
                        //            {
                        //                lock (o)
                        //                {

                        //                    if (!token.IsCancellationRequested)
                        //                    {
                        //                        // SpinWait.SpinUntil(() => Cancel == "取消");
                        //                        SpinWait.SpinUntil(() => false, 100);
                        //                        tag += 1;
                        //                        currentTag = tag;
                        //                        // Thread.Sleep(300);
                        //                        Console.WriteLine($"当前值{currentTag}");
                        //                        entity.Sum = tag;
                        //                    }
                        //                }
                        //            }
                        //        }, token);
                        //        List.Add(t);
                        //    }


                        #endregion
                    }

                    if (Cancel == "取消")
                    {
                        entity.Cancel.Cancel();
                        var cl     = entity.Cancel.IsCancellationRequested;
                        var result = entity.Cts.IsCancellationRequested;
                        entity.Cts.Register(() =>
                        {
                            //不返回了,直接实体赋值
                            log.Info($"Canceled 当前值为{entity.Sum}");
                            //Console.WriteLine($"Canceled 当前值为{entity.Sum}");
                        });
                        //System.Environment.Exit(0); 全部线程退出
                    }
                    //var result = Task.WhenAll(List).ConfigureAwait(true).GetAwaiter();
                    //var result = Task.WhenAll(List).GetAwaiter().GetResult();
                    Task.WaitAll(List.ToArray());
                    return(entity.Sum);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    //throw;
                }
                finally
                {
                    entity.Cancel.Dispose();
                }
                return(entity.Sum);  //设置了200ms延迟 要想正常就去掉延迟就行了
            }
        /// <summary>
        ///		Called to request that the task controller run a task.
        /// </summary>
        /// <param name="runTask">
        ///		The <see cref="RunTask"/> request message.
        /// </param>
        void OnRunTask(RunTask runTask)
        {
            if (runTask == null)
                throw new ArgumentNullException("runTask");

            Log.Information(
                "{ActorPath}: Received request to run task: {What} ({TotalTaskCount} tasks now active)",
                Self.Path.ToUserRelativePath(),
                runTask.What,
                ++_outstandingTaskCount
            );

            _taskRunnerRouter.Tell(
                new StartTask(runTask.What)
            );
        }