I have a windows service running that deletes folders from network drive. I want to make the deleting asynchronous. How can this be done?
Right now i am looping through the directories and calling
Directory.Delete(fullPath, true); Thanks
I would use the Task Parallel Library:
Task.Factory.StartNew(path => Directory.Delete((string)path, true), fullPath); Directory.Delete in a task; which (may - probably) will be a thread from Thread Pool. This will allow your code to continue while the delete is happening on another thread.Task.Factory.StartNew method should not be used without configuring the TaskScheduler parameter explicitly. Even better don't use the Task.Factory.StartNew, and use Task.Run instead.If you are looping, you could use a parallel foreach
// assuming that you have a list string paths. // also assuming that it does not matter what order in which you delete them Parallel.ForEach(theListOfDirectories, x => Directory.Delete(x)); Parallel.ForEach method without specifying the MaxDegreeOfParallelism leads to thread-pool starvation. It is preferable to configure this option in order to get a consistent behavior, and not let the degree of parallelism be determined by how many threads happen to be currently available in the ThreadPool.
Application.DoEventsis for WinForms applications. Windows services do not have a message loop.