Ejemplo n.º 1
0
    public ProcessingQueue(DoWork callback)
    {
      OnDoWork += callback;

      _worker = new Thread(Work);
      _worker.IsBackground = true;
      _worker.Start();
    }
Ejemplo n.º 2
0
        public void WorkItOut()
        {
            DoWork dw = new DoWork(DoWorkMethodImpl);
            //C# Magic,  same as the above, C# writes the IL to create the delegate object,
            //no more "new Delegate()"
            //DoWork dw = DoWorkMethodImpl;

            int i = dw("DoWorkMethodImpl1");
        }
Ejemplo n.º 3
0
        private Thread InitializeGenericWorker(DoWork workMethod, int SleepSeconds, bool sleepAtStart)
        {
            WorkerInfo workerInfo = new WorkerInfo();
            workerInfo.CampfireInfo = CampfireInfo;
            workerInfo.SleepSeconds = SleepSeconds;
            workerInfo.SleepAtStart = sleepAtStart;
            workerInfo.WorkFunc = workMethod;
            workerInfo.CreateEventLogEntryIfNotConfigured = firstWorker;
            firstWorker = false;
            workerInfo.API = new CampfireAPI.API(SmokeSignalConfig.Instance.CampfireName, SmokeSignalConfig.Instance.CampfireToken);

            return StartWorker(workerInfo);
        }
Ejemplo n.º 4
0
        public string Run(TimeSpan?timeout, Persistence.Models.User user)
        {
            var        cache   = new InMemoryRepositoryModelCache();
            var        deleted = 0;
            var        skipped = 0;
            ListFilter filter  = null;

            DoWork.UntilTimeout(((int?)timeout?.TotalSeconds) ?? 5, () =>
            {
                var result = _taskRepository.Clean(user, filter, cache);

                deleted += result.Deleted;
                skipped += result.Skipped;
                filter   = result.NextFilter;

                return(result.Done);
            });

            return(deleted + " tasks cleaned up, " + skipped + " tasks skipped");
        }
Ejemplo n.º 5
0
        public Task StopAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Deteniendo.");

            _timer?.Change(Timeout.Infinite, 0);

            using (var scope = scopeFactory.CreateScope())
            {
                var    _context = scope.ServiceProvider.GetRequiredService <PruebaDBContext>();
                DoWork registro = new DoWork();
                registro.EstaBorrado = false;
                registro.Evento      = "Stop";
                registro.Fecha       = DateTime.Now;

                _context.DoWork.AddAsync(registro);
                _context.SaveChangesAsync();
            }

            return(Task.CompletedTask);
        }
 private void RunTask()
 {
     ThreadInvoker.BackInvoke(() => {
         try {
             DoWork?.Invoke(this, new DoWorkEventArgs(this));
             window.Dispatcher.Invoke(() => {
                 window.Close();
                 RunWorkerCompleted?.Invoke(this, new RunWorkerCompletedEventArgs(null, null, CancellationPending));
             });
         }
         catch (Exception ex) {
             window.Dispatcher.Invoke(() => {
                 window.Close();
                 RunWorkerCompleted?.Invoke(this, new RunWorkerCompletedEventArgs(null, ex, CancellationPending));
             });
         }
     });
     window.Owner         = Application.Current.MainWindow;
     window.ShowInTaskbar = false;
 }
Ejemplo n.º 7
0
        private void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (this.IsEmpty == false)
            {
                List <T> works = new List <T>();

                while (this.IsEmpty == false)
                {
                    if (this.TryDequeue(out T result))
                    {
                        works.Add(result);
                    }
                }

                if (works.Count > 0)
                {
                    DoWork?.Invoke(works);
                }
            }
        }
Ejemplo n.º 8
0
    //string itemName = ((TextBox)this.GridView1.Rows[e.RowIndex].FindControl("aaa")).Text;
    //更新
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //1、获得ID
        string id = this.GridView1.DataKeys[e.RowIndex].Value.ToString();

        string sysName   = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
        string itemName  = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
        string itemValue = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;

        //执行更新命令
        bool success = DoWork.Diction_UpdateItem(id, sysName, itemName, itemValue);

        //取消编辑模式
        this.GridView1.EditIndex = -1;
        //显示状态信息
        statusLabel.Text = success? "更新成功":"更新失败";

        //重载该网格
        BindGrid();
    }
Ejemplo n.º 9
0
        void OnCompleted(IAsyncResult asyncResult)
        {
            //Must call EndInvoke() to prevent resource leaks
            AsyncResult result = (AsyncResult)asyncResult;
            DoWork      doWork = (DoWork)result.AsyncDelegate;

            doWork.EndInvoke(asyncResult);

            if (CancelPending)
            {
                UpdateStatus("Status: Cancelled");
            }
            else
            {
                UpdateStatus("Status: Completed");
            }
            CancelPending = false;

            EnableControl(m_CancelButton, false);
            EnableControl(m_StartButton, true);
        }
Ejemplo n.º 10
0
        public Task StartAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Ejecutándose.");

            _timer = new Timer(DoWork, null, TimeSpan.Zero,
                               TimeSpan.FromSeconds(10));

            using (var scope = scopeFactory.CreateScope())
            {
                var _context = scope.ServiceProvider.GetRequiredService <PruebaDBContext>();

                DoWork registro = new DoWork();
                registro.EstaBorrado = false;
                registro.Evento      = "Start";
                registro.Fecha       = DateTime.Now;

                _context.DoWork.AddAsync(registro);
                _context.SaveChangesAsync();
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 重复每隔interval毫秒执行一次action委托,执行count次后,执行finishAction委托。isActionStart指定是否本方法刚调用就执行一次。
        /// </summary>
        /// <param name="interval"></param>
        /// <param name="count"></param>
        /// <param name="isActionStart"></param>
        /// <param name="action"></param>
        /// <param name="finishAction"></param>
        public static void Invoke(int interval, int count, bool isActionStart, DoWork action, Action finishAction = null)
        {
            if (action == null || count <= 0)
            {
                return;
            }
            int HasCount = 0;

            if (isActionStart)
            {
                HasCount++; action(HasCount); if (HasCount >= count)
                {
                    if (finishAction != null)
                    {
                        finishAction();
                    }
                    return;
                }
            }
            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork             += (ss, ee) => { Thread.Sleep(interval); };
            bw.RunWorkerCompleted += (ss, ee) => { HasCount++; action(HasCount); if (HasCount >= count)
                                                   {
                                                       if (finishAction != null)
                                                       {
                                                           finishAction();
                                                       }
                                                       return;
                                                   }
                                                   else
                                                   {
                                                       bw.RunWorkerAsync();
                                                   } };
            bw.RunWorkerAsync();
        }
Ejemplo n.º 12
0
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //1、获得ID
        string id = this.GridView1.DataKeys[e.RowIndex].Value.ToString();

        GridViewRow row = GridView1.Rows[e.RowIndex];

        string aXingMing = ((TextBox)row.Cells[1].Controls[0]).Text;
        string aSex      = ((DropDownList)row.Cells[2].FindControl("DropDownList2")).SelectedValue;

        string aMobilephone = ((TextBox)row.Cells[3].Controls[0]).Text;
        string aEmail       = ((TextBox)row.Cells[4].Controls[0]).Text;

        //执行更新命令
        bool success = DoWork.Persons_UpdateItem(id, aXingMing, aSex, aMobilephone, aEmail);

        //取消编辑模式
        this.GridView1.EditIndex = -1;
        //显示状态信息
        statusLabel.Text = success ? "更新成功" : "更新失败";

        //重载该网格
        BindGrid();
    }
Ejemplo n.º 13
0
        private static void CallBack(IAsyncResult r)
        {
            DoWork d = (DoWork)r.AsyncState;

            Console.WriteLine("异步调用完成,返回结果为{0}", d.EndInvoke(r));
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Raises the DoWork event.
 /// </summary>
 /// <param name="e">A <see cref="QueuedWorkerDoWorkEventArgs"/> that contains event data.</param>
 protected virtual void OnDoWork(QueuedWorkerDoWorkEventArgs e)
 {
     DoWork?.Invoke(this, e);
 }
Ejemplo n.º 15
0
 public void ShowDialog(object owner = null)
 {
     DoWork?.Invoke(this, new DoWorkEventArgs(null));
     RunWorkerCompleted?.Invoke(this, new RunWorkerCompletedEventArgs(null, null, false));
 }
Ejemplo n.º 16
0
        private void QueueManager()
        {
            while (_running && !_tokenSource.IsCancellationRequested)
            {
                try
                {
                    _processQueueSemaphore.WaitOne(1000);
                }
                catch { } // log no error in the case that this thread is aborted.

                try
                {
                    while (_executeRequests.Count > 0 && !_tokenSource.IsCancellationRequested)
                    {
                        T    request = _defaultValue;
                        Task newTask = null;

                        // Before we dequeue a request we check to ensure we can process it.
                        // loop over all our workers to find one that is not busy.
                        lock (_runningTasks)
                        {
                            foreach (Task worker in _runningTasks)
                            {
                                if (!worker.IsCompleted)
                                {
                                    continue;
                                }

                                _runningTasks.Remove(worker);
                                break;
                            }

                            if (_runningTasks.Count < _maxWorkers)
                            {
                                try
                                {
                                    // Get the next request.
                                    lock (_executeRequests)
                                        request = _executeRequests.Dequeue();
                                }
                                catch { } // log no error in the case there is nothing to dequeue

                                if (request != null && !request.Equals(_defaultValue))
                                {
                                    newTask = _taskFoctory.StartNew(() =>
                                    {
                                        try
                                        {
                                            DoWork?.Invoke(this, request);
                                        }
                                        catch (Exception ex)
                                        {
                                            APILogger.LogError(ex, "Error on invoking Do work in queue factory. {0}", GetName());
                                        }
                                    });

                                    _runningTasks.Add(newTask);
                                }
                            }
                        }

                        if (newTask == null)
                        {
                            _allWorkersBusySemaphore.WaitOne(100); // so we do not get into a tight loop if all workers are busy.
                        }
                    }
                }
                catch (Exception ex)
                {
                    APILogger.LogError(ex);
                }
            }

            _shutdownSemaphore.Set();
        }
Ejemplo n.º 17
0
 //GridView绑定
 private void BindGrid()
 {
     GridView1.DataSource = DoWork.Diction_SelectAll();
     GridView1.DataBind();
 }
Ejemplo n.º 18
0
 public void RegisterCommand(Command cmd, DoWork func)
 {
     commands[cmd] = new ProcessorCommand(func);
 }
        public void RunBackgroundOperationAsync()
        {
            DoWork?.Invoke(this);

            _timer.Stop();
        }
Ejemplo n.º 20
0
 public IAsyncResult BeginDisplayInitializationUI(IClientChannel channel, AsyncCallback callback, object state)
 {
     Console.WriteLine("Begin");
     d = new DoWork(DisplayInitializationUI);
     return(d.BeginInvoke(null, null));
 }
Ejemplo n.º 21
0
 //Work needs DoWork function as first argument
 public double Work(DoWork dw, double k)
 {
     return(dw(k));
 }
Ejemplo n.º 22
0
        private void btnProcess_Click(object sender, EventArgs e)
        {
            DoWork work = new DoWork(PayslipParserWork);

            progressBar1.BeginInvoke(work);
        }
 /// <summary>
 ///     Handle the <see cref="BackgroundWorker.DoWork" /> event to make custom callback.
 /// </summary>
 /// <param name="sender">The sender or the event.</param>
 /// <param name="e">The argument of the event.</param>
 private void Worker_DoWork(object sender, DoWorkEventArgs e)
 {
     DoWork?.Invoke(this, EventArgs.Empty);
 }
 /// <summary>
 /// Raises the System.ComponentModel.Custom.Generic.BackgroundWorker.DoWork event.
 /// </summary>
 /// <param name="e">A System.ComponentModel.Custom.Generic.DoWorkEventArgs
 /// that contains the event data.</param>
 protected virtual void OnDoWork(DoWorkEventArgs <TArgument, TResult> e)
 {
     DoWork?.Invoke(this, e);
 }
Ejemplo n.º 25
0
 //
 private void BindComboBoxBySystem()
 {
     xtmc.DataSource = DoWork.Diction_SelectSysName();
     xtmc.DataBind();
 }
Ejemplo n.º 26
0
 public void RegisterCommand(string command, DoWork func, PlayerRights rightsRequired)
 {
     commands[command.ToLower()] = new ProcessorCommand(func, rightsRequired);
 }
Ejemplo n.º 27
0
 public ProcessorCommand(DoWork function)
 {
     Function = function;
 }
Ejemplo n.º 28
0
 public ProcessorCommand(DoWork function, PlayerRights rightsRequired)
 {
     Function       = function;
     RightsRequired = rightsRequired;
 }
Ejemplo n.º 29
0
 public void RegisterEvent(Command cmd, DoWork func)
 {
     events[cmd] = new ProcessorCommand(func);
 }
Ejemplo n.º 30
0
        public int DoSomething()
        {
            DoWork <int, string> doWork = DoSomeUsefulWork;

            return(doWork("This is an example of generic delegate"));
        }
Ejemplo n.º 31
0
 public void Init()
 {
     DoWork?.Invoke();
 }
Ejemplo n.º 32
0
 public SortingWorker(DoWork dw)
 {
     this.dw = dw;
 }
Ejemplo n.º 33
0
 //选择所有记录
 private void BindGrid()
 {
     GridView1.DataSource = DoWork.Department_SelectAll();
     GridView1.DataBind();
 }