background worker thread
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)
开发者_C百科 {
//ignore files being in use
}
MessageBox.Show("Files Cleaned");
}
}
else
{
MessageBox.Show("Please put a check by the files you want to delete");
}
}
}
}
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.
Have a look at these questions:
Cross-Threading issue with listView
How to execute code in the GUI Thread
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.
精彩评论