Esempio n. 1
0
        public dynamic Emitir()
        {
            if (DateTime.Now <= new DateTime(2018, 10, 31))
            {
                ThreadTask.IniciarThread(() => IntegradorSEFAZ.MonitorarOutput(DiretorioDoOutput));

                var xmlCFe = CFe.Serialize();

                xmlCFe = xmlCFe.Replace("nItem=\"01\"", "nItem=\"1\"").Replace("nItem=\"02\"", "nItem=\"2\"").Replace("nItem=\"03\"", "nItem=\"3\"")
                         .Replace("nItem=\"04\"", "nItem=\"4\"").Replace("nItem=\"05\"", "nItem=\"5\"").Replace("nItem=\"06\"", "nItem=\"6\"")
                         .Replace("nItem=\"07\"", "nItem=\"7\"").Replace("nItem=\"08\"", "nItem=\"8\"").Replace("nItem=\"09\"", "nItem=\"9\"");

                var id = IdSessao.Random();

                xmlCFe.Write(DiretorioDosCupons + "\\CFe_" + CodigoDaFilial + CFe.infCFe.ide.numeroCaixa + id + ".xml");

                var xmlIntegrador = xmlCFe.GerarVendaViaIntegrador(id);
                xmlIntegrador.Write(DiretorioDoInput + "\\Venda_" + CodigoDaFilial + CFe.infCFe.ide.numeroCaixa + id + ".xml");

                dynamic retorno = null;
                do
                {
                    retorno = RetornosProcessados.Where(rp => rp.Sessao == id).FirstOrDefault();
                } while (retorno == null);

                return(retorno);
            }
            else
            {
                throw new Exception("O uso da biblioteca de emissão expirou!");
            }
        }
Esempio n. 2
0
        public void EnQueue(ThreadTask o, bool spin)
        {
            // If the queue is full, wait for an item to be removed
            while (queue.Count >= maxSize)
            {
                if (terminate)
                {
                    throw new CollectionTerminatedException();
                }
                if (!spin || processorCount == 1)
                {
                    Factory.Parallel.Yield();
                }
                enqueueSpins++;
            }
            enqueueSpins += Lock(spin);
            ThreadTask task = (ThreadTask)o;

            queue.Enqueue(task);

            // We always need to pulse, even if the queue wasn't
            // empty before. Otherwise, if we add several items
            // in quick succession, we may only pulse once, waking
            // a single thread up, even if there are multiple threads
            // waiting for items.
            UnLock();
        }
Esempio n. 3
0
        public void ThreadTestTest()
        {
            ThreadTask threadTask = new ThreadTask();
            string     str        = threadTask.ThreadTest();

            Assert.AreEqual(str, "1234test");
        }
Esempio n. 4
0
        public ThreadTask Dequeue(bool spin)
        {
            ThreadTask retVal = null;

            // If the queue is empty, wait for an item to be added
            // Note that this is a while loop, as we may be pulsed
            // but not wake up before another thread has come in and
            // consumed the newly added object. In that case, we'll
            // have to wait for another pulse.
            while (retVal == null)
            {
                if (terminate)
                {
                    throw new CollectionTerminatedException();
                }
                if (!spin || processorCount == 1)
                {
                    Factory.Parallel.Yield();
                }
                dequeueSpins++;
                enqueueSpins += Lock(spin);
                if (queue.Count > 0)
                {
                    retVal = queue.Dequeue();
                }
                UnLock();
            }
            return(retVal);
        }
Esempio n. 5
0
 public void Respond(ThreadTask <T> .ThreadTaskDelegate messageDelegate)
 {
     LogOutput();
     if (threadException != null)
     {
         Log.Error(threadException);
     }
     while (true)
     {
         ThreadTask <T> task;
         lock (TasksLock)
         {
             if (Tasks.Count == 0)
             {
                 break;
             }
             task = Tasks.Dequeue();
         }
         task.Respond(messageDelegate);
         if (task.State == ThreadTask <T> .ThreadTaskState.Error)
         {
             Log.Error(task.Error);
         }
         else if (QueueResponses)
         {
             lock (ResponsesLock)
             {
                 Responses.Enqueue(task);
             }
         }
     }
 }
Esempio n. 6
0
        private void ExecuteWorkOnce(bool shouldWaitForWork = true)
        {
            ThreadTask threadTask = null;

            if (shouldWaitForWork == false && _tasks.TryTake(out threadTask) == false)
            {
                return;
            }

            if (threadTask == null)
            {
                threadTask = GetNextTask();
            }

            if (threadTask == null)
            {
                return;
            }

            if (Interlocked.CompareExchange(ref threadTask.Proccessing, 1, 0) == 1)
            {
                return;
            }

            RunThreadTask(threadTask);
        }
Esempio n. 7
0
        public ActionResult CheckWarehouse()
        {
            try
            {
                TaskFactory factory    = System.Web.HttpContext.Current.Application.Get("TaskFactory") as TaskFactory;
                ThreadTask  threadTask = new ThreadTask("出貨倉資料同步工作");
                MyHelp.Log("Warehouses", null, "出貨倉資料同步");

                lock (factory)
                {
                    threadTask.AddWork(factory.StartNew(Session =>
                    {
                        threadTask.Start();

                        string message = "";
                        HttpSessionStateBase session = (HttpSessionStateBase)Session;

                        try
                        {
                            SyncProcess Sync = new SyncProcess(session);
                            message          = Sync.Sync_Warehouse();
                        }
                        catch (Exception e)
                        {
                            message = e.InnerException != null && !string.IsNullOrEmpty(e.InnerException.Message) ? e.InnerException.Message : e.Message;
                        }

                        return(message);
                    }, HttpContext.Session));
                }
            }
            finally { }

            return(Content(JsonConvert.SerializeObject(new { status = true, message = "Sync starting!" }), "appllication/json"));
        }
Esempio n. 8
0
        /// <summary>
        /// Check and apply aoi from a certain seeekr.
        /// </summary>
        /// <param name="seeker">our seeker.</param>
        /// <param name="distance">seeking distance</param>
        public static void CheckTargets(UNSeeker seeker, float distance)
        {
            if (ThreadManager.instance == null)
            {
                return;
            }

            UNTarget target;
            ThreadTask <UNTarget, UNSeeker, Vector3, bool> task;

            for (int i = 0; i < worldTargets.Count; i++)
            {
                target = worldTargets[i];

                if (target.InDistance(seeker))
                {
                    task = new ThreadTask <UNTarget, UNSeeker, Vector3, bool>((UNTarget _target, UNSeeker _seeker, Vector3 _seekerPos, bool playing) =>
                    {
                        _target.Check(_seeker, _seekerPos, _seeker.seekingDistance, playing);
                    }, target, seeker, target.FixPosition(seeker.transform.position), Application.isPlaying);

                    if (target.useMultithreadedCheck)
                    {
                        ThreadManager.instance.RunOnThread(task);
                    }
                    else
                    {
                        task.Invoke();
                    }
                }
            }
        }
Esempio n. 9
0
        private void RunThreadTask(ThreadTask threadTask)
        {
            try
            {
                threadTask.Duration = Stopwatch.StartNew();

                try
                {
                    if (threadTask.Database?.Disposed == true)
                    {
                        logger.Warn($"Ignoring request to run threadTask because the database ({threadTask.Database.Name}) is been disposed.");
                        return;
                    }
                    _runningTasks.TryAdd(threadTask, null);
                    threadTask.Action();
                }
                finally
                {
                    if (threadTask.BatchStats != null)
                    {
                        Interlocked.Increment(ref threadTask.BatchStats.Completed);
                    }
                    threadTask.Duration.Stop();
                    object _;
                    _runningTasks.TryRemove(threadTask, out _);
                }
            }
            catch (Exception e)
            {
                logger.ErrorException(
                    $"Error occured while executing RavenThreadPool task ; Database name: {threadTask?.Database?.Name} ; " +
                    $"Task queued at: {threadTask?.QueuedAt} ; Task Description: {threadTask?.Description}", e);
            }
        }
Esempio n. 10
0
        private void UpdatePurchaseOrder(Packages package, int reTry = 0)
        {
            try
            {
                TaskFactory factory    = System.Web.HttpContext.Current.Application.Get("TaskFactory") as TaskFactory;
                ThreadTask  threadTask = new ThreadTask(string.Format("直發商待出貨區 - 更新訂單【{0}】以及PO【{1}】資料至SC", package.OrderID, package.POId));

                lock (factory)
                {
                    threadTask.AddWork(factory.StartNew(session =>
                    {
                        threadTask.Start();

                        string error = "";

                        try
                        {
                            HttpSessionStateBase Session = (HttpSessionStateBase)session;
                            SyncProcess Sync             = new SyncProcess(Session);
                            error = Sync.Update_PurchaseOrder(package.ID);
                        }
                        catch (Exception e)
                        {
                            error = e.InnerException != null && !string.IsNullOrEmpty(e.InnerException.Message) ? e.InnerException.Message : e.Message;
                        }

                        return(error);
                    }, HttpContext.Session));
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Starts a new thread task.
        /// </summary>
        /// <remarks>
        /// <para>
        /// There is no need to call <see cref="WatchTask" /> on the returned task.
        /// </para>
        /// </remarks>
        /// <param name="name">The name of the task, or null to create a new name based
        /// on the method associated with the action.</param>
        /// <param name="action">The action to perform.</param>
        /// <returns>The new thread task.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="action"/> is null.</exception>
        public static ThreadTask StartThreadTask(string name, Action action)
        {
            ThreadTask task = CreateThreadTask(name, action);

            task.Start();
            return(task);
        }
Esempio n. 12
0
        private ThreadTask GetNextTask()
        {
            ThreadTask threadTask = null;

            var timeout = 1000;

            while (!_ct.IsCancellationRequested)
            {
                if (_tasks.TryTake(out threadTask, timeout, _ct))
                {
                    break;
                }

                _threadHasNoWorkToDo.Set();
                if (Thread.VolatileRead(ref _hasPartialBatchResumption) == 0)
                {
                    timeout = 5 * 60 * 1000;
                }
                else
                {
                    timeout = 2 * 1000;
                }
            }
            _freedThreadsValue.Value = false;
            return(threadTask);
        }
Esempio n. 13
0
        public IDisposable RunDelay(Action callback, float seconds = 5)
        {
            var task = new ThreadTask();

            task.IsDisposed = false;
            RunUpdate(callback, seconds, task);
            return(task);
        }
Esempio n. 14
0
        public IDisposable RunUpdate(Action <double> callback)
        {
            var task = new ThreadTask();

            task.IsDisposed = false;
            RunUpdate(callback, task);
            return(task);
        }
Esempio n. 15
0
 public void Wake(ThreadTask task)
 {
     _task = task;
     if (_task != null)
     {
         _event.Set();
     }
 }
Esempio n. 16
0
            private static ThreadTask CreateSTAThread(Action start)
            {
                var task = new ThreadTask("AutoCAD Command Runner", start)
                {
                    ApartmentState = ApartmentState.STA
                };

                return(task);
            }
Esempio n. 17
0
        async void RunUpdate(Action callback, float seconds, ThreadTask task)
        {
            await Task.Delay(TimeSpan.FromSeconds(seconds));

            if (!task.IsDisposed)
            {
                callback();
            }
        }
Esempio n. 18
0
        public ActionResult CheckPurchaseItem()
        {
            SyncResult result = new SyncResult();

            try
            {
                IRepository <Packages> Packages = new GenericRepository <Packages>(db);
                IRepository <Items>    Items    = new GenericRepository <Items>(db);

                string[] productIDs = Packages.GetAll(true).Where(p => p.ProcessStatus == (int)EnumData.ProcessStatus.待出貨).Join(Items.GetAll(true), p => p.ID, i => i.PackageID, (p, i) => i.ProductID).Distinct().ToArray();

                if (productIDs.Length == 0)
                {
                    return(Content(JsonConvert.SerializeObject(result.set_error("沒有需要同步的產品!")), "appllication/json"));
                }

                TaskFactory factory    = System.Web.HttpContext.Current.Application.Get("TaskFactory") as TaskFactory;
                ThreadTask  threadTask = new ThreadTask("產品序號同步工作");

                lock (factory)
                {
                    threadTask.AddWork(factory.StartNew(Session =>
                    {
                        threadTask.Start();

                        string message = "";
                        HttpSessionStateBase session = (HttpSessionStateBase)Session;

                        try
                        {
                            SyncProcess Sync = new SyncProcess(session);
                            message          = Sync.Sync_PurchaseItem(productIDs);
                        }
                        catch (DbEntityValidationException ex)
                        {
                            var errorMessages = ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage);
                            message           = string.Join("; ", errorMessages);
                        }
                        catch (Exception e)
                        {
                            message = e.Message;
                        }

                        return(message);
                    }, HttpContext.Session));
                }

                result.taskID = threadTask.ID;
            }
            catch (Exception e)
            {
                return(Content(JsonConvert.SerializeObject(result.set_error(e.Message)), "appllication/json"));
            }

            return(Content(JsonConvert.SerializeObject(result), "appllication/json"));
        }
 private void getSessionTokenTask_Completed(object result)
 {
     if (result != null) //incase theres an expcetion getting sessiontoken
     {
         uploadTask            = new ThreadTask();
         uploadTask.RunTask   += uploadTask_RunTask;
         uploadTask.Completed += uploadTask_Completed;
         uploadTask.Start(result);
     }
 }
Esempio n. 20
0
    public ThreadTask <T> AddTask(T info)
    {
        ThreadTask <T> task = new ThreadTask <T>(info);

        lock (TasksLock)
        {
            Tasks.Enqueue(task);
        }
        return(task);
    }
Esempio n. 21
0
 private void RaiseWork(BackgroundWorker worker, ThreadTask task)
 {
     task.Status    = TaskStatus.Processing;
     task.StartTime = SystemTimeHelper.Now();
     worker.RunWorkerAsync(task);
     if (OnTaskStart != null)
     {
         OnTaskStart(this, new TaskEventArgs(task.Id, task.DisplayName, task.TransactionParamsObj));
     }
 }
Esempio n. 22
0
        public ActionResult GetOrder(List <string> orderIDs)
        {
            SyncResult result = new SyncResult();

            if (!orderIDs.Any())
            {
                return(Content(JsonConvert.SerializeObject(result.set_error("沒有取得訂單號碼!")), "appllication/json"));
            }

            try
            {
                TaskFactory factory = System.Web.HttpContext.Current.Application.Get("TaskFactory") as TaskFactory;

                foreach (string orderID in orderIDs)
                {
                    ThreadTask threadTask = new ThreadTask(string.Format("訂單管理區 - 訂單【{0}】資料同步", orderID));

                    lock (factory)
                    {
                        threadTask.AddWork(factory.StartNew(Session =>
                        {
                            threadTask.Start();

                            string message = "";
                            HttpSessionStateBase session = (HttpSessionStateBase)Session;

                            try
                            {
                                SyncProcess Sync = new SyncProcess(session);
                                message          = Sync.Sync_Order(int.Parse(orderID));
                            }
                            catch (DbEntityValidationException ex)
                            {
                                var errorMessages = ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage);
                                message           = string.Join("; ", errorMessages);
                            }
                            catch (Exception e)
                            {
                                message = e.InnerException != null && !string.IsNullOrEmpty(e.InnerException.Message) ? e.InnerException.Message : e.Message;
                            }

                            return(message);
                        }, HttpContext.Session));
                    }
                }
            }
            catch (Exception e)
            {
                return(Content(JsonConvert.SerializeObject(result.set_error(e.Message)), "appllication/json"));
            }

            return(Content(JsonConvert.SerializeObject(result), "appllication/json"));
        }
Esempio n. 23
0
        /// <summary>
        /// Update the AOI of the finder.
        /// </summary>
        /// <param name="finder">the finder you want to update the AOI zone of.</param>
        public static void UpdateAOI(BaseAOIFinder finder)
        {
            ThreadTask <BaseAOIFinder> task = new ThreadTask <BaseAOIFinder>(ComputeAOI, finder);

            UpdatePositions();

            #if !UNITY_WEBGL
            ThreadManager.RunOnUConstructThread(task);
            #else
            ThreadManager.RunOnUnityThread(task);
            #endif
        }
Esempio n. 24
0
        private string SyncData(ThreadTask threadTask, string syncType, object args = null)
        {
            threadTask.Start();

            string Dir  = Server.MapPath("~/DataSync/");
            string data = null;

            switch (syncType)
            {
            case "Orders":
                int day = Convert.ToInt32(args.ToString());
                Response.Write("--- Get Orders from " + Today.AddDays(-day).ToString() + " to " + Today.ToString() + " ---");
                data = day.ToString();
                break;

            case "PurchaseItem":
                string[] productIDs = args as string[];
                if (productIDs != null)
                {
                    data = string.Join("|", productIDs);
                }
                break;
            }

            Process process = new Process()
            {
                StartInfo = new ProcessStartInfo()
                {
                    FileName               = Dir + "DataSync.exe",
                    Arguments              = string.Format("{0} {1}", syncType, data),
                    UseShellExecute        = false,
                    CreateNoWindow         = false,
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true
                }
            };

            process.Start();
            process.WaitForExit();

            string error  = process.StandardError.ReadToEnd();
            string output = process.StandardOutput.ReadToEnd();

            if (process != null)
            {
                process.Close();
                process.Dispose();
            }

            return(error);
        }
Esempio n. 25
0
        private void ExecuteSingleBatchSynchronously <T>(IList <T> src, Action <T> action, string description, DocumentDatabase database)
        {
            var threadTask = new ThreadTask
            {
                Action     = () => { action(src[0]); },
                BatchStats = new BatchStatistics
                {
                    Total     = 1,
                    Completed = 0
                },
                EarlyBreak  = false,
                QueuedAt    = DateTime.UtcNow,
                Description = new OperationDescription
                {
                    From      = 1,
                    To        = 1,
                    Total     = 1,
                    PlainText = description
                },
                Database = database
            };

            try
            {
                _runningTasks.TryAdd(threadTask, null);
                if (database?.Disposed == true)
                {
                    logger.Warn($"Ignoring request to run a single batch because the database ({database.Name}) is been disposed.");
                    return;
                }
                threadTask.Action();
                threadTask.BatchStats.Completed++;
            }
            catch (Exception e)
            {
                if (logger.IsDebugEnabled)
                {
                    logger.DebugException(
                        "Error occured while executing RavenThreadPool task ; " +
                        $"Database name: {threadTask.Database?.Name} ; Task queued at: {threadTask.QueuedAt} ; " +
                        $"Task Description: {threadTask.Description}", e);
                }

                throw;
            }
            finally
            {
                object _;
                _runningTasks.TryRemove(threadTask, out _);
            }
        }
Esempio n. 26
0
    static public void RunTask()
    {
        if (numRunningTasks < maxRunningTasks && tasks.Count > 0)
        {
            ThreadTask t = tasks.Dequeue();

            ThreadPool.QueueUserWorkItem(
                new WaitCallback(delegate(object ob)
            {
                t.RunTask();
            }), null);
            t.StartCoroutine(t.WaitForCallback());
        }
    }
Esempio n. 27
0
        async void RunUpdate(Action <double> callback, ThreadTask task)
        {
            var    startTime = DateTime.UtcNow;
            double delta;

            while (!task.IsDisposed)
            {
                //60 fps
                delta     = (DateTime.UtcNow - startTime).TotalMilliseconds;
                startTime = DateTime.UtcNow;
                callback(delta);
                await Task.Delay(16);
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Called when the item has returned to the Pool
        /// </summary>
        public virtual void OnReturnedToPool()
        {
            used   = false;
            locked = false;
            uid    = -1;

            ThreadTask <PoolItem> task = new ThreadTask <PoolItem>((PoolItem item) =>
            {
                if (!item.used)
                {
                    item.gameObject.SetActive(false);
                }
            }, this);

            ThreadManager.instance.RunOnUnityThread(task);
        }
Esempio n. 29
0
        public static void Main(string[] args)
        {
            ThreadTask threadTask = new ThreadTask();

            try
            {
                threadTask.Start();
                BuildWebHost(args).Run();

                threadTask.Stop();
            }
            catch
            {
                threadTask.Stop();
            }
        }
Esempio n. 30
0
        public void AlgorithmTest()
        {
            ThreadTask task = new ThreadTask();
            List <int> org  = new List <int>();

            org.Add(2);
            org.Add(3);
            org.Add(7);
            org.Add(1);
            org.Add(4);

            string str = task.Algorithm(org);


            Assert.AreEqual("12347", str);
        }
Esempio n. 31
0
 public static void QueueTask(ThreadTask t)
 {
     tasks.Enqueue(t);
     RunTask();
 }
Esempio n. 32
0
 public static void FinishTask(ThreadTask t)
 {
     numRunningTasks--;
     runningTasks.Remove(t);
     RunTask();
 }