public void CancellationWorks() { using (var f = new ProgressForm()) { f.Show(); //Necessary to make Visible work var cancelButton = (Button)f.Controls.Find("cancelButton", true)[0]; Assert.IsFalse(cancelButton.Visible); f.AllowCancellation = true; Assert.IsTrue(cancelButton.Visible); Assert.IsFalse(f.WasCanceled); cancelButton.PerformClick(); Assert.IsTrue(f.WasCanceled); } }
public static bool Execute(IWin32Window parent, Action<IProgressReporter> method) { if (method == null) throw new ArgumentNullException("method"); Exception exception = null; bool canceled = false, finished = false; using (var dialog = new ProgressForm()) { dialog.Show(parent); ThreadPool.QueueUserWorkItem(delegate { try { method(dialog); } catch (Exception ex) { exception = ex; } finally { canceled = dialog.WasCanceled; finished = true; dialog.BeginInvoke(new Action(dialog.Close)); } }); if (!dialog.IsDisposed && !finished) { dialog.Hide(); dialog.ShowDialog(parent); //Only show modally if the operation hasn't finished yet; this avoids a brief flicker for very quick operations } } if (exception != null) throw new TargetInvocationException(exception); return !canceled; }