I have Add button click event
how add file:
private void btnAddfiles_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == Sys
I just had the same problem, this worked for me.
private void Worker_DoWork(object sender, EventArgs e)
{
if (Worker.IsBusy == false) { //...Finished execution }
}
To prevent UI freezing, you can do this:
while (BackgroundWorker.IsBusy()) {
Application.DoEvents();
}
I go this from the msdn docs, here
Most easy way is to keep a counter.
private int numWorkers = 0;
Then increment it as you start each background worker.
using (stream)
{
Interlocked.Increment(ref numWorkers);
StartBackgroundFileChecker(file);
}
Assign Same method as event completed to each background worker.
backgroundWorker.RunWorkerCompleted += myCommonCompletedHandler;
Decrement counter in completed event.
public void myCommonCompletedHandler(object sender, RunWorkerCompletedEventArgs e)
{
if(Interlocked.Decrement(ref numWorkers) == 0)
{
// all complete
}
}
You may use this approch with only one BackgroundWorker
.
BackgroundWorker backgroundWorker;
private void btnAddfiles_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.DoWork +=
(s3, e3) =>
{
StartBackgroundFileChecker(openFileDialog1.FileNames);
};
backgroundWorker.ProgressChanged +=
(s3, e3) =>
{
//example:
this.progressBar1.Value = e.ProgressPercentage;
};
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
(s3, e3) =>
{
///End Here!!
});
backgroundWorker.RunWorkerAsync();
}
}
private void StartBackgroundFileChecker(string[] files)
{
for (int i = 0; i < files.Length; i++)
{
string file = files[i];
System.IO.Stream stream;
try
{
if ((stream = openFileDialog1.OpenFile()) != null)
{
using (stream)
{
ListboxFile listboxFile = new ListboxFile();
listboxFile.OnFileAddEvent += listboxFile_OnFileAddEvent;
//Other things...
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
backgroundWorker.ReportProgress((i+1) * 100.0/files.Length, file);
}
}