10

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

11
  • Very hard to see why that would be a requirement in a service, they already use threads. You could use another. Commented Jan 20, 2012 at 22:04
  • Put your directory delete in a method, and call it asynchronously. Very simple. Here is a great tutorial. You can also use asynchronous callbacks/events to post progress updates; codeproject.com/Articles/14931/Asynchronous-Method-Invocation Commented Jan 20, 2012 at 22:05
  • Why should a Windows service do things asynchronously? It runs in the background anyway. Asynchronous operations are usually used in order to keep the UI responsive instead of freezing it during long running operations. Commented Jan 20, 2012 at 22:06
  • 1
    @OlivierJacot-Descombes: A windows service should be responsive to start/stop requests. Commented Jan 20, 2012 at 22:11
  • 1
    @OlivierJacot-Descombes: Application.DoEvents is for WinForms applications. Windows services do not have a message loop. Commented Jan 20, 2012 at 22:37

2 Answers 2

11

I would use the Task Parallel Library:

Task.Factory.StartNew(path => Directory.Delete((string)path, true), fullPath); 
Sign up to request clarification or add additional context in comments.

5 Comments

+1; beat me to it. And kudos for using the lighter-weight approach of passing the parameter instead of closing over the local.
@vcsjones : will this be like call the method asynchronously and then it will be picked by io thread later ?
@stackoverflowuser This will call 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.
@vcsjones Isn't this against what is mentioned here: blogs.msdn.com/b/pfxteam/archive/2012/03/24/10287244.aspx ? I surely dont grok the async subject much I think.
The 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.
1

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)); 

1 Comment

FYI using the 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.