0

Writing part of an application that is supposed to clean up any old files, but some of these are quite large so i start some BackgroundWorkers to do the bulk of the work. My question is, if i am calling a file.Delete call on a FileInfo object on a BackgroundWorker and the application exits:

  • What will happen to that file, is it going to hang around in an invalid state?
  • Will the application hang, or will the BGWorker stay alive?
  • Is the file left invalid?
  • Is BackgroundWorker the correct class to be using in this case?
Craig
  • 1,199
  • 1
  • 13
  • 27
  • I think background worker is the right choice for this kind of operation. I probably cant answer all of your questions but here are some of the answers: No application won't hang as background worker runs of different thread. Once the background worker starts processing the file I think it might go to in invalid state. Have you though of using Task Parallel Library, it basically does the same thing but in much easier way. – qamar Aug 21 '13 at 02:24
  • if you're worried your application will exit unexpectedly and these are some truly large files, you could create a windows service that exposes a delete queue. This would in effect be your backgroundWorker wrapper. If you want to delete a file, why are you worried if it will be invalid? Or do you just want to make sure it's really deleted? – mrtig Aug 21 '13 at 02:37
  • Just want to make sure it is really gone mostly. I'm not so worried about it exiting unexpectedly, but the application user may chose to quit the application, not knowing there are files being deleted. I would like to keep it as transparent as possible. – Craig Aug 21 '13 at 02:42

2 Answers2

0

Ok, to get around this issue i have switched to using the Thread object. This creates a foreground thread, and application shouldn't exit until all foreground threads have been completed.

Sorry about the hassle.

Craig
  • 1,199
  • 1
  • 13
  • 27
0

If you just want your application thread to wait till the file is deleted, you can use the BackgroundWorker combined with an AutoResetEvent. This is explained at How to wait for a BackgroundWorker to cancel? (Please note that this answer contains additional info on cancelling too)

This way, you still have the advantages of having events exposed by BackgroundWorker, such as ProgressChanged and RunWorkerCompleted.

Ofcourse, creating fore-ground threads is another work-around that works, coz they block the main thread until they exit. But may not be the most elegant solution.

Community
  • 1
  • 1
Tharaka
  • 2,355
  • 1
  • 20
  • 22