I have the backgroundworker and cross-thread know issue.. I read a lot of material about the problem in some forums but I still stuck.
I build IO project that contain win form shows the user details about copy\paste files (such as how much items remaining, time, progress bar, etc.)
[I send for IO constructor 3 fields: ActionType _act(to Copy \ Delete),List<String[]> sources,String _target)]
I get the follow error just when I delete files (I success to copy but not to delete, really strange…):
"An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
Additional information: Cross-thread operation not valid: Control 'IO' accessed from a thread other than the thread it was created on."
I'm not call any control from DoWork event handler:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { // Copy if (act == ActionType.Copy) copyFiles(sender, e); // > Work Perfect :) // Delete if (act == ActionType.Delete) deleteFiles(sender, e); // > Doesn't working, fail on pb_CopyDeleteTime.Value = e.ProgressPercentage; in ProgressChanged event /* I also try it instead */ //if (act == ActionType.Delete) //BeginInvoke((MethodInvoker)delegate //{ // After debugging I found this block not happened // deleteFiles(sender, e); //}); }
I update my GUI in ProgressChanged event:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { pb_CopyDeleteTime.Value = e.ProgressPercentage; // I get the error here if I not using BeginInoke method // ... code ... }
I also give the user option to close the form (and cancel the copy \ paste operation) like this:
private void IO_FormClosing(object sender, FormClosingEventArgs e) { // if the user cancel the operation by click on the close form ('X') lock (_lock) { // If the list is not null and has workers if (backgroundWorker1 != null) { // If the worker is busy - cancel it if (backgroundWorker1.IsBusy) { backgroundWorker1.CancelAsync(); e.Cancel = true; return; } } } }
When the operation finish the form close automatically:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) MessageBox.Show("Error occur while performing the action", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); // I GET THE ERROR HERE, if I use BeginInvoke method and nothing delete }
As I write in the comments I get the error on this.Close, in RunWorkerCompleted event -> Although I called BeginInvoke method, my deleteFiles function not performed.
or on pb_CopyDeleteTime.Value = e.ProgressPercentage in ProgressChanged event -> I get the error on starting…
Maybe, someone know why?
Thank you!