-1

I am trying to figure out the best way to keep my application responsive. Below shows the code that I am currently working with. What i have found is that the Background worker thread is the way to go.

    private void cleanFiles()
    {
            if (listView1.CheckedItems.Count != 0)
            {

                // If so, loop through all checked files and delete.

                foreach (ListViewItem item in listView1.CheckedItems)
                {

                    string fileName = item.Text;
                    string filePath = Path.Combine(tFile + fileName);

                    try
                    {

                        File.Delete(filePath);
                    }
                    catch (Exception)
                    {
                        //ignore files being in use
                    }

                    MessageBox.Show("Files Cleaned");
                }


            }
            else
            {
                 MessageBox.Show("Please put a check by the files you want to delete");
            }

        }


    }

    }
partialdata
  • 93
  • 4
  • 14

3 Answers3

1

The easiest way to keep your program responsive is to use the BackgroundWorker.

List<string listWithFilenames = new List<string>();
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync(listWithFilenames);

See the documentation.

Jaapjan
  • 3,365
  • 21
  • 25
0

Have a look at these questions:

Cross-Threading issue with listView

How to execute code in the GUI Thread

Community
  • 1
  • 1
Iain Ward
  • 9,850
  • 5
  • 34
  • 41
0

assuming that the method you posted runs under the context of the UI thread, all you need to do is wrap the logic (the foreach part) in a method like :

private void DeleteFiles(object state)
{
/// your logic here
}

and call the ThreadPool.QueueWorkItem(new WaitCallback(DeleteFiles)); from the cleanfiles method.

if you run .NET 4.0, you can use something like:

Task myTask = Task.Factory.StartNew( () => DoWork(null)); then check the myTask status later , to see if its done.

Menahem
  • 3,974
  • 1
  • 28
  • 43