9

I'm developping an application and I have a problem with a deadlock.

My code looks like that :

Process p = new Process(); // That using an other application

Then I'm sending an .xml-file to this process:

XmlSerializer xs = new XmlSerializer(data.GetType());
using (var ms = new MemoryStream())
{
    var sw = new StreamWriter(ms);
    XmlWriter xmlwriter = XmlWriter.Create(sw, xmlWriterSettings);
    xmlwriter.WriteProcessingInstruction("PipeConfiguratorStyleSheet", processing);
    xs.Serialize(xmlwriter, data);
    xmlwriter.Flush();
    ms.Position = 0;
    var sr = new StreamReader(ms);
    while (!sr.EndOfStream)
    {
        String line = sr.ReadLine();
        p.StandardInput.WriteLine(line);                
        Console.WriteLine(line);
        p.BeginOutputReadLine();
        p.CancelOutputRead(); 
    }
}

So actually I can send a part of my .xml-file to my process but at some point I'll get a deadlock. I guess I don't knoy how to use BeginOutputReadLine() correctly.

12
  • isn't there a method to use the Process-instance directly as a stream? like xs.Serialize(p.StandardInput, data)?
    – user57508
    Commented Oct 15, 2014 at 14:19
  • Are you sure the receiving side is reading the data in? If the receiving side is not reading when the buffer gets full you can get blocked. Do you have the code for the receiving side? Commented Oct 15, 2014 at 14:21
  • how do you encounter the deadlock? I am asking, because there is no lock - so it is not fully obvious, to me, how there should be a hang (which could be described as a deadlock)...
    – user57508
    Commented Oct 15, 2014 at 14:23
  • I don't know really. I used a basic Write() / Read() but it's a synchronized method. And according to my research i have to use desynchronized method as BeginOutputReadLine().
    – stbr
    Commented Oct 15, 2014 at 14:23
  • Why are you calling canceloutputread()? Can you locate where it's deadlocking at? Deadlock occurs when there is a contention for the same resource, so I'm not seeing where it can occur.
    – Luminous
    Commented Oct 15, 2014 at 14:26

1 Answer 1

3

First off, why don't you use the Process.StandardInput-property directly as your target, like

var process = new Process
{
    // all your init stuff
};
var xmlSerializer = new XmlSerializer(data.GetType());
var xmlwriter = XmlWriter.Create(process.StandardInput, xmlWriterSettings);
xmlSerializer.Serialize(xmlwriter, data);

Otherwise, the msdn-entry gives a clear howto for using Process.BeginOutputReadLine(), which you can remodel to

var autoResetEvent = new AutoResetEvent(false); // this mutex acts as our bouncer for the reading-part
var process = new Process
{
    // all your init stuff
};
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, args) => {
    // TODO you could read the content here with args.Data
    autoResetEvent.Set();
};
process.Start();

using (var memoryStream = new MemoryStream())
{
    using (var streamWriter = new StreamWriter(memoryStream))
    {
        var xmlSerializer = new XmlSerializer(data.GetType());
        var xmlwriter = XmlWriter.Create(streamWriter, xmlWriterSettings);
        xmlSerializer.Serialize(xmlwriter, data);
    }
    memoryStream.Position = 0;
    using (var streamReader = new StreamReader(memoryStream))
    {
        while (!streamReader.EndOfStream)
        {
            var line = streamReader.ReadLine();
            process.StandardInput.WriteLine(line);

            Console.WriteLine(line);

            process.BeginOutputReadLine();
            autoResetEvent.WaitOne();
        }
    }
}

// TODO closing the process.StandardInput, exiting process, ...

Anyway - I know this should be a comment - is there a specific reason why you are waiting for your process to write something?

The StandardOutput stream can be read synchronously or asynchronously. Methods such as Read, ReadLine, and ReadToEnd perform synchronous read operations on the output stream of the process. These synchronous read operations do not complete until the associated Process writes to its StandardOutput stream, or closes the stream. In contrast, BeginOutputReadLine starts asynchronous read operations on the StandardOutput stream. This method enables a designated event handler for the stream output and immediately returns to the caller, which can perform other work while the stream output is directed to the event handler.

Which means, that if your process does not write anything (and you are waiting), you are spinning for response endlessly ...

EDIT

You should additionally add a handler to Process.ErrorDataReceived like

process.StartInfo.RedirectStandardError = true;
process.ErrorDataReceived += (sender, args) => {
    // TODO do something with the response of args.Data
    autoResetEvent.Set();
};

and

while (!streamReader.EndOfStream)
{
    var line = streamReader.ReadLine();
    process.StandardInput.WriteLine(line);

    Console.WriteLine(line);

    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
    autoResetEvent.WaitOne();
}

to handle error-cases as well (whatever that may mean).

5
  • The program isn't work like that for me. I'll try to resolve errors with your answers and send the final code. Thk a lot.
    – stbr
    Commented Oct 15, 2014 at 15:40
  • Hi, after some data print i got this error :An async read operation has already been started on the stream. Do you know how can i resolve this ? Thank's.
    – stbr
    Commented Oct 16, 2014 at 9:22
  • @SteevenBrunner This happens when you call .BeginOutputReadLine() without previously being called-back with .OutputDataReceived. This is why I've used AutoResetEvent. Which approach did you actually tried and which are you currently using? Could you propably put this information in your question?
    – user57508
    Commented Oct 16, 2014 at 10:01
  • My program works now. The problem was that i didn't read the error output, my process returned somes warning so that blocked the execution. I didn't used the autoResetEvent() because my process didn't returned each times something. Thank's a lot for your help =)
    – stbr
    Commented Oct 16, 2014 at 12:57
  • @SteevenBrunner I've adapted my answer and added a hint for adding an error-handler as well.
    – user57508
    Commented Oct 16, 2014 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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