Hi,
In a form main class's specific button(Process button) event, I call a backgroundworker controls dowork method.
In the 'DoWork' method : I create an instance of another "ProcessFiles" class
And I am calling a particular method of this ProcessFilesclass in a background thread.
This background class method reads set of files in the directory(in a for loop) and does some processing/filtering and creates some set of config files in another folder.
Now User clicks on another button(Stop) in the form, I cancel the background worker process by calling cancelasync. And It will call 'Dispose()' method of the ProcessFiles class also. This dispose method is implemented by inheriting 'Idisposable' interface. And this method will delete the directory after cleaning up all objects. Here is my problem. I get an exception"The process cannot access the file xxx, because it is being used by another process". Surprisingly this issue doesnt occur all the time. Only in 1 instance out of 6-7 times, this issue occurs.
I dont know how I can attack this issue. When I debug, I am not able to find what is locking the file.
Please help me!
Below is my code!
protected virtual void Dispose(bool disposing) { if(!this.disposed) { if(disposing) { if (_writer != null) { _writer.Close(); _writer.Dispose(); } if (dir != null) { dir.Dispose(); } p = null; _writer = null; dir = null; } CloseHandle(fo); fo = null; // Note disposing has been done. disposed = true; } } // Use interop to call the method necessary // to clean up the unmanaged resource. [System.Runtime.InteropServices.DllImport("Kernel32")] private extern static Boolean CloseHandle(StreamReader fo); private string readfileContents(string strfile) { try { if (_writer != null) { string data = ""; fo = new System.IO.StreamReader(strfile, System.Text.Encoding.Default); data = fo.ReadToEnd(); fo.Close(); fo.Dispose(); fo = null; return data; } else return ""; } catch (Exception ex) { fo.Close(); fo.Dispose(); fo = null; return ""; } finally { fo.Close(); fo.Dispose(); fo = null; } } public void IndexDocs(string file, bool bOnce) { try { if (_writer != null) { if (System.IO.Directory.Exists(Path.GetFullPath(file))) { System.String[] files = System.IO.Directory.GetFileSystemEntries(Path.GetFullPath(file)); if (files != null) { for (int i = 0; i < files.Length; i++) { if (_writer != null) { IndexDocs(Path.GetFullPath(files[i]), bOnce); } else return; } } } else { .......
.................
IndexDocument(file);
....................
................... } } } else return; } catch(Exception ex) { } } public void IndexDocument(string f) { try { if (_writer != null) { ......................
...................... fld = new Field("contents", readfileContents(Path.GetFullPath(f)), Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.NO); ...................... } } catch (Exception ex) { } finally { } }