1

I have 2 programs, one is serializing XXXX.xml, and the other deserialize XXXX.xml.temp file. the 2 programs are individual and uses different threads that are happening every predefined interval.

Following is the code that reads the xml. here i am getting the following exception:

The process cannot access the file '' because it is being used by another process.

    private void StartDiskFlushThread()
    {
        _flushThread = new Thread(ThreadProc);
        _flushThread.IsBackground = true;
        _flushThread.Start();
    }

    private void ThreadProc()
    {
        try
        {
            while (_flushThread.IsAlive)
            {
                FlushStepsToFile();
                Thread.Sleep(_flushInterval);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            Log.Error("ThreadProc failed", ex);
        }
    }

    private void FlushStepsToFile()
    {
        try
        {
            SerializeSteps(1);
        }
        catch (Exception ex)
        {
            Log.Error("Failed to flush steps to disk, retrying", ex);
            Thread.Sleep(1000);
            SerializeSteps(2);
        }
    }

    private void SerializeSteps(int trycount)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(DetailedSteps));
        try
        {
            using (TextWriter textWriter = new StreamWriter(_targetFileLocation))
            {
                serializer.Serialize(textWriter, _detailedSteps);
            }
        }
        catch (Exception ex)
        {
            Log.ErrorFormat("SerializeSteps method failed. try #{0}. Error:{1}", trycount, ex);
        }
    }

As for the code that reads the xml. The program is also a thread that copies the XXXX.xml to XXXX.xml.temp and than reads the temp file.

    private void CopyPartialLog()
    {
        try
        {
            File.Copy(ReportFile, DestReportFile, true);
        }
        catch (Exception ex)
        {
            Log.Error("CopyPartialLog failed", ex);
        }
    }

i have no exceptions there because i am reading different file: XXXX.xml.temp

following is the exception i am getting from the first program that writes the xml:

7077846 [SerializeSteps method failed. try #1. Error:System.IO.IOException: The process cannot access the file 'xxxx.xml' because it is being used by another process. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)

the exception i am getting is hanging my writer thread and i don't understand why. what do you suggest? how can i resolve it?

4 Answers 4

2

You can't read when some other process is writing and you can't write when some other process is reading (it has to read the file to copy it; so the whole copying might be pointless in the end).

How about using a FileSystemWatcher on the reader that will get notified once the file is written (and closed)? The writer could use a FileSystemWatcher to track when the file is being read or wait till that's done.

As an alternative, use some other form of inter-process communication, e.g. TCP/IP, shared memory, etc.

Or - maybe a bit more tricky (you could run into deadlocks if you're not careful): Use a Mutex to synchronize.

1
  • As an alternative, I would just check if I get that exception as an indication that it is still in use. I mean, really, that is why it's their - that exception. But +1 for the FileSystemWatcher suggestion! Commented Jun 14, 2012 at 8:58
1

I had a similiar issue, in a multi-threaded application, where different threads were trying to access the same object. Try using the lock statement, for each object that access the file, to prevent simultaneous access to the same file.

2
0

I had a nearly identical problem working with Xml because I had instantiated XmlReader & XmlWiter at the same time (You are using different methods, but have the same issue). What I did was to set up the reader/writer variables in the class, but not to instantiate them until their own, separate method.

public class XmlTool
{
    public static string filepath = @"C:\\This\That\Folder";
    private static XmlReader reader;
    private static XmlWriter writer;

    public static void Write2Xml(string s)
    {
        writer = XmlWriter.Create(filepath);
        /* Do Stuff */
        writer.Close( );
    }

    public static string ReadFromXml( )
    {
        reader = XmlReader.Create(filepath);
        /* Do Stuff */
        reader.Close( );
    }
}

So, the reader and writer are only instantiated while their method is running, and then closed when the method is finished. This code is not exact, but I can send you the original with comments if you think it would help. Hope that explains a bit!

0

As @CM90 said I had the same issue I was loading XML reader and had Subscribed to events for methods in the Initializer += and since those events were linking to the method that was using XML Writer code it crashed and said that the program is already being used by another program so Placing those Events that I subscribed in the initializer After the XML Reader that is in Form_Load fixed this. Now I have the XML writer code in my settings Tab when I open it with a button and the Reader at the Load separate. Glad I found this answered but cant upvote it yet

Not the answer you're looking for? Browse other questions tagged or ask your own question.