public ProcessingQueue(DoWork callback) { OnDoWork += callback; _worker = new Thread(Work); _worker.IsBackground = true; _worker.Start(); }
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"); }
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); }
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"); }
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; }
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); } } }
//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(); }
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); }
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); }
/// <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(); }
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(); }
private static void CallBack(IAsyncResult r) { DoWork d = (DoWork)r.AsyncState; Console.WriteLine("异步调用完成,返回结果为{0}", d.EndInvoke(r)); }
/// <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); }
public void ShowDialog(object owner = null) { DoWork?.Invoke(this, new DoWorkEventArgs(null)); RunWorkerCompleted?.Invoke(this, new RunWorkerCompletedEventArgs(null, null, false)); }
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(); }
//GridView绑定 private void BindGrid() { GridView1.DataSource = DoWork.Diction_SelectAll(); GridView1.DataBind(); }
public void RegisterCommand(Command cmd, DoWork func) { commands[cmd] = new ProcessorCommand(func); }
public void RunBackgroundOperationAsync() { DoWork?.Invoke(this); _timer.Stop(); }
public IAsyncResult BeginDisplayInitializationUI(IClientChannel channel, AsyncCallback callback, object state) { Console.WriteLine("Begin"); d = new DoWork(DisplayInitializationUI); return(d.BeginInvoke(null, null)); }
//Work needs DoWork function as first argument public double Work(DoWork dw, double k) { return(dw(k)); }
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); }
// private void BindComboBoxBySystem() { xtmc.DataSource = DoWork.Diction_SelectSysName(); xtmc.DataBind(); }
public void RegisterCommand(string command, DoWork func, PlayerRights rightsRequired) { commands[command.ToLower()] = new ProcessorCommand(func, rightsRequired); }
public ProcessorCommand(DoWork function) { Function = function; }
public ProcessorCommand(DoWork function, PlayerRights rightsRequired) { Function = function; RightsRequired = rightsRequired; }
public void RegisterEvent(Command cmd, DoWork func) { events[cmd] = new ProcessorCommand(func); }
public int DoSomething() { DoWork <int, string> doWork = DoSomeUsefulWork; return(doWork("This is an example of generic delegate")); }
public void Init() { DoWork?.Invoke(); }
public SortingWorker(DoWork dw) { this.dw = dw; }
//选择所有记录 private void BindGrid() { GridView1.DataSource = DoWork.Department_SelectAll(); GridView1.DataBind(); }