internal UploadMediaInfoWorker(FileInfo inputFile) { Logger.Info("Starting new UploadMediaInfoWorker on " + inputFile.FullName); this.inputFile = inputFile; DoWork += new DoWorkEventHandler(UploadMediaInfoWorker_DoWork); }
public FormInfo(Form owner, string Message, DoWorkEventHandler DoWork, RunWorkerCompletedEventHandler RunWorkerCompleted) { doInitialize(owner, Message, DoWork, RunWorkerCompleted, null); }
/// <summary> /// Constructor that accepts Event handlers for executing async thread /// </summary> /// <param name="WorkerProcess">Worker Process Handler</param> /// <param name="WorkProgressHandler">Progress Changed Event Handler</param> /// <param name="WorkCompletedHandler">Call back method handler which is invoked once the Worker Process is completed</param> public WorkerHelper(DoWorkEventHandler WorkerProcess, ProgressChangedEventHandler WorkProgressHandler, RunWorkerCompletedEventHandler WorkCompletedHandler) { this.DoWork += WorkerProcess; this.ProgressChanged += WorkProgressHandler; this.RunWorkerCompleted += WorkCompletedHandler; this.WorkerReportsProgress = true; }
public BackgroundConnectionHelper(DoWorkEventHandler AsyncDelegate, RunWorkerCompletedEventHandler GUIDelegate, ProgressChangedEventHandler ProgressChanged) { backgroundWorker = new BackgroundWorker(); backgroundWorker.DoWork += AsyncDelegate; backgroundWorker.RunWorkerCompleted += GUIDelegate; backgroundWorker.ProgressChanged += ProgressChanged; }
public BackgroundConnectionHelper(DoWorkEventHandler AsyncDelegate, RunWorkerCompletedEventHandler GUIDelegate) { backgroundWorker = new BackgroundWorker(); backgroundWorker.DoWork += AsyncDelegate; backgroundWorker.RunWorkerCompleted += GUIDelegate; backgroundWorker.WorkerSupportsCancellation = true; }
public ProcessBackground(int Max, DoWorkEventHandler DoWork, ProgressChangedEventHandler worker_ProgressChanged)//最大值和标题 { progressForm = new FrmAutoUpdate(); progressForm.progressBarDownload.Value = 0; progressForm.Show(); SetbackgroundWorker(DoWork, worker_ProgressChanged); }
private static void RegisterDoWork(this BackgroundWorker bw, DoWorkEventHandler doWorkEvent = null) { bw.WorkerSupportsCancellation = true; //默认实现 if (doWorkEvent == null) { doWorkEvent = (sender, e) => { var ce = e.Argument as CustomerDoWorkEventArgs;//获取传递参数 BackgroundWorker cBw = ce.ExecBackgroundWorker; int count = Convert.ToInt32(ce.ExecParameter.ToString(), 10); for (int i = 0; i < count; i++) { if (!cBw.CancellationPending)//永远可以取消 { //汇报当前处理进度 cBw.ReportProgress(i, "正在处理第" + i + "条数据"); Thread.Sleep(500); } else { e.Cancel = true; return; } } e.Result = "执行操作完成的结果:1"; }; } bw.DoWork += doWorkEvent; }
/// <summary> /// Initializes a new instance of the <see cref="AsyncWorker"/> class. /// </summary> /// <param name="name">The name used in log messages.</param> /// <param name="worker">The worker delegate.</param> /// <param name="completed">The completed delegate.</param> public AsyncWorker( string name, DoWorkEventHandler worker, RunWorkerCompletedEventHandler completed) : this(name, worker, null, completed) { }
public QBDepositWorker(DailyDeposit dailyDeposit) { _dailyDeposit = dailyDeposit; DoWork += new DoWorkEventHandler(QBDepositWorker_DoWork); WorkerReportsProgress = true; WorkerSupportsCancellation = true; }
/// <summary> /// Shows loading form and executes given action as async background worker. /// </summary> /// <param name="action">Async action to execute</param> /// <param name="Text">Text to display on loading form</param> /// <param name="invertOrder">true - action will be runned first, loading form will be showed as second action | false - first will be showed loading form, second will be executed given action</param> /// <param name="sleep">delay in ms to wait between given action and loading form showing</param> public void runAsyncLoadingAction(DoWorkEventHandler action, String Text, bool invertOrder = false, int sleep=0) { this.Enabled = false; loadingText = Text; BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += new DoWorkEventHandler(handleLoading); BackgroundWorker bw2 = new BackgroundWorker(); if (action != null) { bw2.DoWork += new DoWorkEventHandler(action); bw2.RunWorkerCompleted += handleLoadingEnd; } if (!invertOrder) { if (action != null) { bw2.RunWorkerAsync(); if (sleep>0) System.Threading.Thread.Sleep(sleep); } bw.RunWorkerAsync(); } else { bw.RunWorkerAsync(); if (action != null) { if (sleep>0) System.Threading.Thread.Sleep(sleep); bw2.RunWorkerAsync(); } } }
/// <summary> /// ProgressDialogクラスのコンストラクタ /// </summary> /// <param name="caption">タイトルバーに表示するテキスト</param> /// <param name="doWorkHandler">バックグラウンドで実行するメソッド</param> /// <param name="argument">doWorkで取得できるパラメータ</param> public ProgressDialog(string caption, DoWorkEventHandler doWork, object argument) { InitializeComponent(); //初期設定 this.workerArgument = argument; this.Text = caption; this.FormBorderStyle = FormBorderStyle.FixedDialog; this.ShowInTaskbar = false; this.StartPosition = FormStartPosition.CenterParent; this.ControlBox = false; this.CancelButton = this.cancelAsyncButton; this.messageLabel.Text = ""; this.progressBar1.Minimum = 0; this.progressBar1.Maximum = 100; this.progressBar1.Value = 0; this.cancelAsyncButton.Text = "キャンセル"; this.cancelAsyncButton.Enabled = true; this.backgroundWorker1.WorkerReportsProgress = true; this.backgroundWorker1.WorkerSupportsCancellation = true; //イベント this.Shown += new EventHandler(ProgressDialog_Shown); this.cancelAsyncButton.Click += new EventHandler(cancelAsyncButton_Click); this.backgroundWorker1.DoWork += doWork; this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged); this.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted); }
public FormInfo(Form owner, string Message, DoWorkEventHandler DoWork, RunWorkerCompletedEventHandler RunWorkerCompleted, object Argument) { doInitialize(owner, Message, DoWork, RunWorkerCompleted, Argument); }
public static BackgroundWorker InitNewBackgroundWorker(DoWorkEventHandler doWorkEvent, ProgressChangedEventHandler progressChangedEvent, RunWorkerCompletedEventHandler runWorkerCompletedEvent) { var bw = new BackgroundWorker(); bw.RegisterDoWork(doWorkEvent); bw.RegisterProgressChanged(progressChangedEvent); bw.RegisterRunWorkerCompleted(runWorkerCompletedEvent); return bw; }
internal PublishWorkerHost(string outputDirectoryPath) { DoWork += new DoWorkEventHandler(SaveWorkerHost_DoWork); WorkerReportsProgress = true; WorkerSupportsCancellation = true; this.outputDirectoryPath = outputDirectoryPath; }
public ConsoleWorker(int maximumCount) { _countProtector = new Object(); _maxCount = maximumCount; _workerCallback = new AsyncCallback(this.OnRunWorkerCompleted); _eventHandler = new DoWorkEventHandler(this.OnDoWork); }
public void startWork(DoWorkEventHandler work, String description) { if (bg_worker.IsBusy) return; isProgressBarActive = true; StatusText = description; bg_worker.DoWork += work; bg_worker.RunWorkerAsync(); bg_worker.DoWork -= work; }
public DownloadWorker(String id) : base() { Id = id; WorkerReportsProgress = true; WorkerSupportsCancellation = true; DoWork += new DoWorkEventHandler(DownloadWorker_DoWork); }
private void RunBackground(DoWorkEventHandler doWork, object argument, RunWorkerCompletedEventHandler runWorkerCompleted) { using (BackgroundWorker backgroundWorker = new BackgroundWorker()) { backgroundWorker.DoWork += doWork; backgroundWorker.RunWorkerCompleted += runWorkerCompleted; backgroundWorker.RunWorkerAsync(argument); } }
public static double method(int i) { DoWorkEventArgs args = new DoWorkEventArgs(i); DoWorkEventHandler work = new DoWorkEventHandler(bw_DoWork); work(null, args); return (double)args.Result; }
public BackgroundWorkerCommand(DoWorkEventHandler execute, Predicate<object> canExecute) { if (execute == null) { throw new ArgumentNullException("execute"); } DoWork += execute; RunWorkerCompleted += RunWorkerCompletedTrack; this.canExecute = canExecute; }
public BackgroundTask(FrameworkElement optionalRunAsElement, int runDelay, DoWorkEventHandler doWork) : this(optionalRunAsElement, doWork) { if (runDelay > 0) { // Create the run delay timer but don't start it m_RunDelayTimer = new DispatcherTimer(); m_RunDelayTimer.Interval = new TimeSpan(runDelay * TimeSpan.TicksPerMillisecond); m_RunDelayTimer.Tick += RunDelayCompleted; } }
//把事件传进入 private void SetbackgroundWorker(DoWorkEventHandler DoWork, ProgressChangedEventHandler worker_ProgressChanged) { backgroundWorker.WorkerReportsProgress = true;//有进度条 backgroundWorker.WorkerSupportsCancellation = true;//是否支持异步取消 backgroundWorker.DoWork += new DoWorkEventHandler(DoWork); backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);//做的事情 backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(OnProgressChanged);//更新进度条 backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);//完成事件 backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnProcessCompleted); backgroundWorker.RunWorkerAsync(); }
// Offer 4 different cascading constructors public BackgroundTask(bool runOnUIThread, DoWorkEventHandler doWork) { base.WorkerSupportsCancellation = true; if (!runOnUIThread) base.DoWork += doWork; else base.DoWork += delegate(object sender, DoWorkEventArgs e) { Deployment.Current.Dispatcher.BeginInvoke(delegate() { doWork(sender, e); }); }; }
public BackgroundTask(bool runOnUIThread, int runDelay, DoWorkEventHandler doWork) : this(runOnUIThread, doWork) { if (runDelay <= 0) return; // Create the run delay timer but don't start it _RunDelayTimer = new DispatcherTimer(); _RunDelayTimer.Interval = new TimeSpan(runDelay * TimeSpan.TicksPerMillisecond); _RunDelayTimer.Tick += RunDelayCompleted; }
/// <summary> /// Called when an operation is cancelled. /// </summary> /// <param name="asyncWorker">The async worker.</param> /// <param name="worker">The worker.</param> public void CancellingExecution(AsyncWorker asyncWorker, DoWorkEventHandler worker) { if (this.log.IsInfoEnabled) { this.log.Info(string.Format( CultureInfo.InvariantCulture, "{0} cancels asynchronous operation {1}.{2}()", asyncWorker, worker.Method.DeclaringType.FullName, worker.Method.Name)); } }
// ------------------------------------------------------------------- /// <summary> /// Creates a new instance of the background worker dialog. /// </summary> /// <param name="description"> /// The description of the job to be displayed in the dialog. /// </param> /// <param name="marquee"> /// True if the progress bar in the dialog should be a marquee /// (indeterminate progress) instead of a percentage. /// </param> /// <param name="workHandler"> /// The work handler that should be executed to start the job. /// </param> public BackgroundWorkerDialog(string description, bool marquee, DoWorkEventHandler workHandler) { InitializeComponent(); descriptionLabel.Text = description; if (marquee) progressBar.Style = ProgressBarStyle.Marquee; backgroundWorker.DoWork += workHandler; }
public FrmProgressWindow(Form parentForm, string titleRoot, DoWorkEventHandler function) { _parentForm = parentForm; _titleRoot = titleRoot; InitializeComponent(); ClientSize = new Size(511, 131); _titleRoot = titleRoot; bgWork.DoWork += function; }
// Offer 4 different cascading contructors public BackgroundTask(FrameworkElement optionalRunAsElement, DoWorkEventHandler doWork) { m_worker = new BackgroundWorker(); m_worker.WorkerSupportsCancellation = true; if (optionalRunAsElement == null) m_worker.DoWork += doWork; else m_worker.DoWork += delegate(object sender, DoWorkEventArgs e) { optionalRunAsElement.Dispatcher.BeginInvoke(delegate() { doWork(sender, e); }); }; }
internal QuadResCombinBackground( MainForm UseForm, QuadResWorkerInfo WInfo ) { MForm = UseForm; DoWork += new DoWorkEventHandler( QuadResCombinBackground_DoWork ); ProgressChanged += new ProgressChangedEventHandler( QuadResCombinBackground_ProgressChanged ); RunWorkerCompleted += new RunWorkerCompletedEventHandler( QuadResCombinBackground_RunWorkerCompleted ); WorkerReportsProgress = true; WorkerSupportsCancellation = true; ProcessName = WInfo.ProcessName; }
/// <summary> /// Called when an operation is started. /// </summary> /// <param name="asyncWorker">The async worker.</param> /// <param name="worker">The worker.</param> /// <param name="argument">The argument.</param> public void StartedExecution(AsyncWorker asyncWorker, DoWorkEventHandler worker, object argument) { if (this.log.IsInfoEnabled) { this.log.Info(string.Format( CultureInfo.InvariantCulture, "{0} executes asynchronous operation {1}.{2}({3})", asyncWorker, worker.Method.DeclaringType.FullName, worker.Method.Name, argument)); } }
public simworker(SecurityImpl sec) { workersec = sec; WorkerSupportsCancellation = true; RunWorkerCompleted += new RunWorkerCompletedEventHandler(simworker_RunWorkerCompleted); // if we're multi-core prepare to start I/O thread for this security if (Environment.ProcessorCount > 1) { DoWork += new DoWorkEventHandler(simworker_DoWork); workersec.HistSource.gotTick += new TickDelegate(HistSource_gotTick2); } else { workersec.HistSource.gotTick += new TickDelegate(HistSource_gotTick); } }
/// <summary> /// 后台异步运行代码 /// </summary> /// <param name="doWork">需要异步执行方法委托</param> /// <param name="runWorkerCompleted">异步执行完成后的方法委托</param> public static void RunInBackground(DoWorkEventHandler doWork, RunWorkerCompletedEventHandler runWorkerCompleted) { var loadingFrm = new LoadingFrm(); using (var worker = new BackgroundWorker()) { worker.DoWork += doWork; worker.RunWorkerCompleted += delegate(object obj, RunWorkerCompletedEventArgs env) { loadingFrm.Close();//关闭等待窗口 }; worker.RunWorkerCompleted += runWorkerCompleted; worker.RunWorkerAsync(); //执行异步线程 loadingFrm.ShowDialog(); //打开等待窗口 } }
/// <summary> /// Launches a worker thread which is intended to perform /// work while progress is indicated, and displays the dialog /// modally in order to block the calling thread. /// </summary> /// <param name="argument">A custom object which will be /// submitted in the <see cref="DoWorkEventArgs.Argument"/> /// property <paramref name="workHandler"/> callback method.</param> /// <param name="workHandler">A callback method which is /// being invoked on a background thread in order to perform /// the work to be performed.</param> public bool RunWorkerThread(object argument, DoWorkEventHandler workHandler) { if (autoIncrementInterval.HasValue) { //run timer to increment progress bar progressTimer.Interval = TimeSpan.FromMilliseconds(autoIncrementInterval.Value); progressTimer.Start(); } //store reference to callback handler and launch worker thread workerCallback = workHandler; worker.RunWorkerAsync(argument); //display modal dialog (blocks caller) return(ShowDialog() ?? false); }
public AccionAsincronaGenerica(object parametro, DoWorkEventHandler accion) { this.RunWorkerCompleted += this.AccionAsincronaGenericaRunWorkerCompleted; this.ProgressChanged += this.AccionAsincronaGenericaProgressChanged; if (accion != null) { this.DoWork += accion; } else { this.DoWork += this.AccionAsincronaGenericaDoWork; } this.Disposed += this.AccionAsincronaGenericaDisposed; this.RunWorkerAsync(parametro); }
private void patchPspIsoMenuItem_Click(object sender, EventArgs e) { DoWorkEventHandler doWork = delegate(object sender1, DoWorkEventArgs args) { PspIso.PatchISO(sender1 as BackgroundWorker, args, PatchPSPForm); }; ProgressChangedEventHandler progress = delegate(object sender2, ProgressChangedEventArgs args) { progressBar.Visible = true; progressBar.Value = args.ProgressPercentage; }; RunWorkerCompletedEventHandler completed = null; completed = delegate(object sender3, RunWorkerCompletedEventArgs args) { progressBar.Visible = false; Enabled = true; patchPsxBackgroundWorker.ProgressChanged -= progress; patchPsxBackgroundWorker.RunWorkerCompleted -= completed; patchPsxBackgroundWorker.DoWork -= doWork; if (args.Error is NotSupportedException) { MessageBox.Show("File is not a recognized War of the Lions ISO image.", "Error", MessageBoxButtons.OK); } else if (args.Error != null) { HandleException(args.Error); } }; if (PatchPSPForm.CustomShowDialog(this) == DialogResult.OK) { patchPsxBackgroundWorker.ProgressChanged += progress; patchPsxBackgroundWorker.RunWorkerCompleted += completed; patchPsxBackgroundWorker.DoWork += doWork; Enabled = false; progressBar.Value = 0; progressBar.Visible = true; patchPsxBackgroundWorker.RunWorkerAsync(); } }
private void patchPsxIsoMenuItem_Click(object sender, EventArgs e) { PatchPSXForm.patchISO = true; DoWorkEventHandler doWork = delegate(object sender1, DoWorkEventArgs args) { PsxIso.PatchPsxIso(FFTPatch, sender1 as BackgroundWorker, args, PatchPSXForm); }; ProgressChangedEventHandler progress = delegate(object sender2, ProgressChangedEventArgs args) { progressBar.Visible = true; progressBar.Value = Math.Max(progressBar.Minimum, Math.Min(args.ProgressPercentage, progressBar.Maximum)); }; RunWorkerCompletedEventHandler completed = null; completed = delegate(object sender3, RunWorkerCompletedEventArgs args) { progressBar.Visible = false; Enabled = true; patchPsxBackgroundWorker.ProgressChanged -= progress; patchPsxBackgroundWorker.RunWorkerCompleted -= completed; patchPsxBackgroundWorker.DoWork -= doWork; if (args.Error != null) { HandleException(args.Error); } }; if (PatchPSXForm.CustomShowDialog(this, FFTPatch) == DialogResult.OK) { patchPsxBackgroundWorker.ProgressChanged += progress; patchPsxBackgroundWorker.RunWorkerCompleted += completed; patchPsxBackgroundWorker.DoWork += doWork; Enabled = false; progressBar.Value = 0; progressBar.Visible = true; patchPsxBackgroundWorker.RunWorkerAsync(); } }
/// <summary> /// /// </summary> /// <param name="port"></param> /// <param name="progressbarRequest"></param> /// <param name="progressbarResponse"></param> public BackgroundSendReceiver( SerialPort port, ToolStripProgressBar progressbarRequest, ToolStripProgressBar progressbarResponse) { this.port = port; this.progressbarRequest = progressbarRequest; this.progressbarResponse = progressbarResponse; this.WorkerReportsProgress = true; // デリゲートを仕掛ける。 DoWork += new DoWorkEventHandler(SendAndReceive); ProgressChanged += new ProgressChangedEventHandler(ProgressChange); RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedCore); }
public ProgressDialog(DoWorkEventHandler doWork, params object[] arguments) : this() { this.backgroundWorker.DoWork += doWork; if (arguments.Length == 0) { this.workerArgument = null; } else if (arguments.Length == 1) { this.workerArgument = arguments[0]; } else { this.workerArgument = new List <object>(arguments); } }
public static void BackgroundProcess(DoWorkEventHandler workerFunction, RunWorkerCompletedEventHandler completeFunction, object stateVariable = null) { BackgroundWorker bw = new BackgroundWorker(); bw.WorkerSupportsCancellation = false; bw.WorkerReportsProgress = false; bw.DoWork += new DoWorkEventHandler(workerFunction); bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(completeFunction); if (stateVariable != null) { bw.RunWorkerAsync(stateVariable); } else { bw.RunWorkerAsync(); } }
private void RunWithWorker(DoWorkEventHandler doWork) { CheckForIllegalCrossThreadCalls = false; try { multiworker = new BackgroundWorker { WorkerReportsProgress = true }; multiworker.DoWork += doWork; multiworker.RunWorkerAsync(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public GenerateGroupsProgressDialog(Project project, DoWorkEventHandler doWorkEventHandler, bool firstRun) { InitializeComponent(); Text = LocalizationManager.GetString("DialogBoxes.GenerateGroupsProgressDialog.Title", "Optimize Groups"); int numCharacters = project.GetKeyStrokesByCharacterId().Count; int numActors = project.VoiceActorList.Actors.Count; string firstLineOfText = string.Format(LocalizationManager.GetString("DialogBoxes.GenerateGroupsProgressDialog.Overview.AnyRun.Text1", "Script includes {0} distinct Biblical character roles."), numCharacters); string secondLineOfText = string.Format(LocalizationManager.GetString("DialogBoxes.GenerateGroupsProgressDialog.Overview.AnyRun.Text2", "You have entered {0} voice actors."), numActors); string firstLineOfStatusText = string.Format(LocalizationManager.GetString("DialogBoxes.GenerateGroupsProgressDialog.StatusText.AnyRun.Text1", "{0} is creating optimized groups of characters to match the list of actors."), ProductName); Overview = firstLineOfText + Environment.NewLine + secondLineOfText; if (firstRun) { StatusText = firstLineOfStatusText; } else { StatusText = firstLineOfStatusText + Environment.NewLine + string.Format(LocalizationManager.GetString("DialogBoxes.GenerateGroupsProgressDialog.StatusText.SubsequentRun.Text2", "{0} will attempt to maintain any existing voice actor assignments."), ProductName); } OkButtonText = LocalizationManager.GetString("DialogBoxes.GenerateGroupsProgressDialog.Continue", "Continue"); ShowInTaskbar = false; CanCancel = false; ProgressLabelTextWhenComplete = LocalizationManager.GetString("GenerateGroupsProgressDialog.Complete", "Group generation is complete."); BarStyle = ProgressBarStyle.Marquee; BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += doWorkEventHandler; worker.RunWorkerCompleted += (s, e) => { if (e.Error != null) { throw e.Error; } }; BackgroundWorker = worker; }
// WOW UPDATE private void updateWoW() { BackgroundWorker backgroundWorker = new BackgroundWorker(); backgroundWorker.WorkerReportsProgress = true; DoWorkEventHandler workEventHandler = new DoWorkEventHandler(this.worker1_DoWork); backgroundWorker.DoWork += workEventHandler; ProgressChangedEventHandler changedEventHandler = new ProgressChangedEventHandler(this.worker1_ProgressChanged); backgroundWorker.ProgressChanged += changedEventHandler; RunWorkerCompletedEventHandler completedEventHandler = new RunWorkerCompletedEventHandler(this.worker1_Complete); backgroundWorker.RunWorkerCompleted += completedEventHandler; backgroundWorker.RunWorkerAsync(); this.btnPlay.BackgroundImage = global::LauncherV3.Properties.Resources.PlayButtonDisabled; }
/// <summary> /// Begins asynchronous progress display in the progress bar</summary> /// <param name="message">Message to display with progress meter</param> /// <param name="argument">Worker argument</param> /// <param name="workHandler">Background thread delegate</param> /// <param name="progressCompleteHandler">Event handler for work completion event</param> /// <param name="autoIncrement">Whether to auto increment the progress meter</param> public void RunProgressInStatusBarAsync(string message, object argument, DoWorkEventHandler workHandler, EventHandler <ProgressCompleteEventArgs> progressCompleteHandler, bool autoIncrement) { var statusItem = new ProgressViewModel() { Cancellable = false, Description = message, IsIndeterminate = autoIncrement }; // Add the part to the status bar ComposablePart part = m_composer.AddPart(statusItem); statusItem.Tag = new StatusBarProgressContext(progressCompleteHandler, part); statusItem.RunWorkerThread(argument, workHandler); statusItem.RunWorkerCompleted += new EventHandler(statusItem_RunWorkerCompleted); }
/// <summary> /// run task in thread </summary> /// <example> /// This of use doJob method /// <code> /// Job.doJob( /// new DoWorkEventHandler( /// delegate (object o, DoWorkEventArgs args) /// { /// // run in new thread /// } /// ), /// new RunWorkerCompletedEventHandler( /// delegate (object o, RunWorkerCompletedEventArgs args) /// { /// // complete /// } /// ) /// ); /// </code> /// </example> public static void doJob(DoWorkEventHandler doJob = null, RunWorkerCompletedEventHandler afterJob = null) { try { BackgroundWorker bw = new BackgroundWorker { WorkerSupportsCancellation = true }; bw.WorkerReportsProgress = true; bw.DoWork += doJob; bw.RunWorkerCompleted += afterJob; bw.RunWorkerAsync(); } catch (Exception ex) { Program.log.write(ex.Message); } }
public void ExecuteFailingOperation() { AppDomain.CurrentDomain.UnhandledException += this.UnhandledException; DoWorkEventHandler worker = delegate { throw new InvalidOperationException("test"); }; AsyncWorker testee = new AsyncWorker(worker); testee.RunWorkerAsync(); Assert.IsTrue(this.caughtExceptionSignal.WaitOne(TimeOut), "no exception caught"); AppDomain.CurrentDomain.UnhandledException -= this.UnhandledException; }
public static void DoBackgroundWorkWithSplash(IWin32Window sender, DoWorkEventHandler workToDo, string splashText) { var loadingSplash = new FrmLoadingSplash { StartPosition = FormStartPosition.CenterParent }; loadingSplash.SetTitle(splashText); var updateThread = new BackgroundWorker(); updateThread.DoWork += workToDo; updateThread.RunWorkerCompleted += (o, e) => { loadingSplash.WorkCompleted(); }; updateThread.RunWorkerAsync(); loadingSplash.ShowDialog(sender); }
/// <summary> /// Executa um comando async /// </summary> /// <param name="statusProcessamento">Mensagem de processamento</param> /// <param name="work">Handler que será executado em outra thread</param> /// <param name="completed">Handler que será executado quando o <see cref="work"/> terminar</param> /// <param name="userState">Parametro extra para UserState</param> protected void ExecutarComandoAsync(string statusProcessamento, DoWorkEventHandler work, RunWorkerCompletedEventHandler completed, object userState = null) { Processando = true; StatusProcessamento = statusProcessamento; var bw = new BackgroundWorker(); bw.DoWork += work; bw.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs args) { Processando = false; completed(sender, args); }; bw.RunWorkerAsync(userState); }
public static void DoBackgroundWorkWithSplash(IWin32Window sender, DoWorkEventHandler workToDo, string splashText, bool singleThreadApartment = false) { var loadingSplash = new FrmLoadingSplash {StartPosition = FormStartPosition.CenterParent}; loadingSplash.SetTitle(splashText); var thread = new Thread(() => { workToDo(null, null); loadingSplash.WorkCompleted(); }); if (singleThreadApartment) thread.SetApartmentState(ApartmentState.STA); thread.Start(); loadingSplash.ShowDialog(sender); }
public void startAsyncWorkerWithTask(string desc, DoWorkEventHandler asyncWork, CleanupDelegate asyncCleanup, object argument) { if (!asyncWorker.IsBusy) { if (USB.Check_Limit_Switches() && USB.IsOpen) { ExtLog.AddLine("Starting Async Task"); USB.Inhibit_LimitSwitches_Warning = true; HostControl.Enabled = false; try { ExtLog.AddLine(desc); asyncWorker.DoWork += asyncWork; lastTask = asyncWork; CleanupCallback = asyncCleanup; asyncWorker.RunWorkerAsync(argument); } catch (Exception ex) { ExtLog.AddLine("Async Task failed: " + ex.Message); } ExtLog.AddLine("Async Started"); if (taskDialog.ShowDialog(HostControl) == DialogResult.Abort) { cancelTask(); USB.CancelMove(); } HostControl.Enabled = true; USB.Inhibit_LimitSwitches_Warning = false; } else { ExtLog.AddLine("Can't init scripted sequence, limit switches are not properly set or USB interface is Closed"); } } else { ExtLog.AddLine("Async Task Already Running"); } }
public void ExecuteOperation() { AutoResetEvent go = new AutoResetEvent(false); AutoResetEvent workerExecuted = new AutoResetEvent(false); DoWorkEventHandler worker = delegate { go.WaitOne(); workerExecuted.Set(); }; AsyncWorker testee = new AsyncWorker(worker); testee.RunWorkerAsync(); go.Set(); Assert.IsTrue(workerExecuted.WaitOne(TimeOut), "worker did not execute."); }
/// <summary> /// Конструктор. Выполняет указанное действие /// </summary> /// <param name="HardWorkProcess">Выполняемый процесс</param> public HardWorkExecutor(DoWorkEventHandler HardWorkProcess) { // Настройка BackgroundWorker bw.WorkerReportsProgress = true; // Разрешает возвраты изнутри процесса bw.WorkerSupportsCancellation = true; // Разрешает завершение процесса bw.DoWork += ((HardWorkProcess != null) ? HardWorkProcess : DoWork); bw.RunWorkerCompleted += RunWorkerCompleted; bw.ProgressChanged += ProgressChanged; // Донастройка окна InitializeProgressBar(); currentPercentage = (int)ProgressBarSize; AbortButton.FlatStyle = FlatStyle.Standard; // Запуск this.ShowDialog(); }
public void Start(DoWorkEventHandler toDo, ProgressChangedEventHandler onProgress, RunWorkerCompletedEventHandler whenDone) { if (bgWorker != null && bgWorker.IsBusy) { return; } Start(); bgWorker = new BackgroundWorker { WorkerReportsProgress = onProgress != null }; bgWorker.DoWork += toDo; bgWorker.ProgressChanged += onProgress; bgWorker.RunWorkerCompleted += whenDone; bgWorker.RunWorkerAsync(); }
protected virtual void OnDoWork(DoWorkEventArgs e) { mThread = Thread.CurrentThread; DoWorkEventHandler workStartDelegate = (DoWorkEventHandler)base.Events[BackgroundWorkerEx.doWorkKey]; if (workStartDelegate != null) { try { workStartDelegate(this, e); } catch (ThreadAbortException) { Thread.ResetAbort(); } } }
private void RunBackgroundTask(DoWorkEventHandler task, RunWorkerCompletedEventHandler completedHandler) { try { SetControlsState(false); backgroundWorker1 = new BackgroundWorker(); backgroundWorker1.DoWork += task; backgroundWorker1.RunWorkerCompleted += completedHandler; backgroundWorker1.RunWorkerAsync(); } catch (ApplicationException ex) { //SetStatusText(Resources.Error); SetControlsState(); HandleError(ex.Message); } }
/// <summary> /// Executes the specified action worker asynchronously. /// </summary> /// <param name="actionName">Name of the action.</param> /// <param name="eventHandler">The event handler.</param> /// <param name="actionWorker">The action worker.</param> /// <param name="completeHandler">The complete handler.</param> public void ExecuteAction(string actionName, DoWorkEventHandler eventHandler, ActionWorker actionWorker, RunWorkerCompletedEventHandler completeHandler) { BackgroundWorker worker; if (!workers.TryGetValue(actionName, out worker)) { worker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true }; worker.ProgressChanged += progressChanged; worker.DoWork += eventHandler; worker.RunWorkerCompleted += completeHandler; workers.Add(actionName, worker); } actionWorker.Worker = worker; worker.RunWorkerAsync(actionWorker); }
/// <summary> /// Start a background task /// </summary> /// <param name="argument"></param> /// <param name="OnWork">This code will be run under the context of the background thread</param> /// <param name="OnInit">This code will run on the owner's thread</param> /// <param name="OnProgress">This code will run on the owner's thread</param> /// <param name="OnComplete">This code will run on the owner's thread</param> /// <returns></returns> public static BackgroundWorker Start( object argument, DoWorkEventHandler OnWork, EventHandler OnInit, ProgressChangedEventHandler OnProgress, RunWorkerCompletedEventHandler OnComplete ) { BackgroundWorker b = NewBackgroundWorker(OnWork, OnProgress, OnComplete); if (OnInit != null) { OnInit(b, EventArgs.Empty); } b.RunWorkerAsync(argument); return(b); }
private void btnInstall_Click(object sender, EventArgs e) { BackgroundWorker backgroundWorker = new BackgroundWorker(); backgroundWorker.WorkerReportsProgress = true; DoWorkEventHandler workEventHandler = new DoWorkEventHandler(this.worker_DoWork); backgroundWorker.DoWork += workEventHandler; ProgressChangedEventHandler changedEventHandler = new ProgressChangedEventHandler(this.worker_ProgressChanged); backgroundWorker.ProgressChanged += changedEventHandler; RunWorkerCompletedEventHandler completedEventHandler = new RunWorkerCompletedEventHandler(this.worker_Complete); backgroundWorker.RunWorkerCompleted += completedEventHandler; backgroundWorker.RunWorkerAsync(); pBar.Visible = true; btnInstall.Visible = false; }
/// <summary> /// Sets up, runs, waits for work to complete, and returns a /// BackgroundWorker with the appropriate parameters. /// </summary> public static BackgroundWorker RunSyncWork(DoWorkEventHandler doWork, RunWorkerCompletedEventHandler workCompleted, ProgressChangedEventHandler progressChanged, bool supportsCancellation, List <object> parameters) { BackgroundWorker worker = SetupBackgroundWorker( doWork, workCompleted, progressChanged, supportsCancellation); AutoResetEvent resetEvent = new AutoResetEvent(false); worker.RunWorkerCompleted += (sender, e) => { resetEvent.Set(); }; worker.RunWorkerAsync(parameters); resetEvent.WaitOne(); return(worker); }
public void CanCancelOperation() { AutoResetEvent workerStarted = new AutoResetEvent(false); AutoResetEvent workerExecuted = new AutoResetEvent(false); AutoResetEvent workerCancelled = new AutoResetEvent(false); AutoResetEvent allowTerminating = new AutoResetEvent(false); bool?cancelled = null; DoWorkEventHandler worker = delegate(object sender, DoWorkEventArgs e) { AsyncWorker genericWorker = (AsyncWorker)sender; genericWorker.WorkerSupportsCancellation = true; workerStarted.Set(); while (!genericWorker.CancellationPending) { Thread.Sleep(1); } e.Cancel = true; workerCancelled.Set(); allowTerminating.WaitOne(); }; RunWorkerCompletedEventHandler completed = delegate(object sender, RunWorkerCompletedEventArgs e) { cancelled = e.Cancelled; workerExecuted.Set(); }; AsyncWorker testee = new AsyncWorker(worker, completed); testee.RunWorkerAsync(); workerStarted.WaitOne(TimeOut).Should().BeTrue("worker should start."); testee.CancelAsync(); workerCancelled.WaitOne(TimeOut).Should().BeTrue("worker should cancel."); allowTerminating.Set(); workerExecuted.WaitOne(TimeOut).Should().BeTrue("worker should execute."); cancelled.Should().BeTrue("result should reflect canceled state."); }
private BackgroundWorker CreateWorker(DoWorkEventHandler doWorkEventHandler, ProgressChangedEventHandler reportProgressEventHandler = null, RunWorkerCompletedEventHandler completedEventHandler = null) { var bw = new BackgroundWorker(); bw.WorkerReportsProgress = reportProgressEventHandler != null; bw.WorkerSupportsCancellation = true; bw.DoWork += new DoWorkEventHandler(doWorkEventHandler); if (reportProgressEventHandler != null) { bw.ProgressChanged += new ProgressChangedEventHandler(reportProgressEventHandler); } if (completedEventHandler != null) { bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(completedEventHandler); } return(bw); }