Tutorial :“used by another process” error



Question:

i have an object that is being accessed by 2 events simulataneously.

first, a user-defined event will access it, then the projectItemsEvent_ItemAdded event, opens it again.

and got this error "The process cannot access the file because it is being used by another process."

please help!

thanks

Code Example:

void ProjectItemEvents_ItemAdded()  {     Util util = new Util(_applicationObject.Solution, CurrentSelectedProject)       if (name != null)     {       util.AddNewObject();     }  }    void addItem(object sender, WebReferenceEventArgs e)  {    try    {      System.Threading.Thread.Sleep(4500);      Util util = new Util(_applicationObject.Solution, CurrentSelectedProject)      util.AddNewObject();    }    catch (Exception ex)    {    }  }  


Solution:1

It sounds like you're opening a file in both of the event handlers (hard to say for sure without code examples).

If you're just reading the file (rather than modifying/overwriting it), you could open it for shared access and allow multiple processes to have the same file open.

FileInfo fi = new FileInfo(@"C:\someFile.txt");  FileStream fs = fi.Open(FileMode.Open, FileAccess.Read, FileShare.Read);  

If you post some code snippets, we might be able to help you integrate the change into what you already have.

UPDATE

After looking at your code, my guess is that there is a File Acess problem inside of the Util class. Can you also post its constructor?


Solution:2

You should probably use the lock keyword, if there is no way for you to avoid the events from colliding.

http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.80).aspx

http://www.toolazy.me.uk/template.php?content=lock(this)_causes_deadlocks.xml


Solution:3

You have to make sure to close the FileStream after you finish reading the file.

FileStream.Close();


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »