First, an ObjectDisposedException is just one possible error. Running the OP code threw the following InvalidOperationException in a significant number of cases:
Invoke or BeginInvoke cannot be invoked on a control until a window handle has been created.
I suppose this could be changed by starting the worker in the "Loaded" callback and not in the constructor, but all this testing can be avoided altogether if the BackgroundWorker Progress reporting mechanism is used. The following works well:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { while (!this.bgWorker.CancellationPending) { this.bgWorker.ReportProgress(Environment.TickCount); Thread.Sleep(1); } } private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { this.textBox1.Text = e.ProgressPercentage.ToString(); }
I kind of hijacked a percentage parameter, but you can use another overload to pass any parameter.
It is interesting to note that removing the aforementioned sleep call clogs the user interface, consumes a high processor and constantly increases memory usage. I assume this is because the message queue is overloaded with a graphical interface. However, when the sleep call is intact, the CPU usage is actually 0, and memory usage seems fine. To be reasonable, perhaps a higher value than 1 ms should be used? An expert opinion will be appreciated here ... Update . It seems that while the update is not too frequent, it should be in order: Link
In any case, I cannot foresee a scenario where the GUI update should be within intervals not exceeding a couple of milliseconds (at least in scenarios where a person is watching the GUI), so I think most of what the time report will be the right choice
Ohad Schneider Jan 25 2018-10-10T00: 00-01
source share