I have WinForm with backgroundWorker:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using SeoTools.Utils; namespace SeoTools.UI { public partial class UIProgress : Form { public UIProgress(DoWorkEventHandler doWorkEventHandler, RunWorkerCompletedEventHandler runWorkerCompletedEventHandler) { InitializeComponent(); this.backgroundWorker.WorkerReportsProgress = true; this.backgroundWorker.WorkerSupportsCancellation = true; this.backgroundWorker.DoWork += doWorkEventHandler; this.backgroundWorker.RunWorkerCompleted += runWorkerCompletedEventHandler; } public void Start() { var foo = SynchronizationContext.Current; backgroundWorker.RunWorkerAsync(); } private void btnStop_Click(object sender, EventArgs e) { btnStop.Enabled = false; btnStop.Text = "Stopping..."; backgroundWorker.CancelAsync(); } private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { try { wdgProgressBar.Value = e.ProgressPercentage; if (this.Visible == false) { this.ShowDialog(); this.Update(); } } catch (InvalidOperationException) {} } private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { this.Hide();
The first time I run this, it works great. But the second time I get an InvalidOperationException
when this.Hide()
called.
"Additional Information: Invalid cross-flow operation: Control 'UIProgress' is drawn from a stream other than the stream on which it was created."
The strange thing about starting foo in Start () the first time is with WindowsFormsSyncronizationContext , but in the second try System.Threading.SyncronizationContext .
The application I'm writing is an ExcelDna plugin.
EDIT
Start () is called as follows:
UIProgress uiProgress = new UIProgress( delegate(object sender, DoWorkEventArgs args) { .... }, delegate(object sender, RunWorkerCompletedEventArgs args) { ... } ); uiProgress.Start();
source share