Question

Je travaille avec un NamedPipeServerStream pour communiquer entre deux processus. Voici le code où j'initialiser et connecter le tuyau:

void Foo(IHasData objectProvider)
{
    Stream stream = objectProvider.GetData();
    if (stream.Length > 0)
    {
        using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("VisualizerPipe", PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
        {
            string currentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string uiFileName = Path.Combine(currentDirectory, "VisualizerUIApplication.exe");
            Process.Start(uiFileName);
            if(pipeServer.BeginWaitForConnection(PipeConnected, this).AsyncWaitHandle.WaitOne(5000))
            {
                while (stream.CanRead)
                {
                    pipeServer.WriteByte((byte)stream.ReadByte());
                }
            }
            else
            {
                throw new TimeoutException("Pipe connection to UI process timed out.");
            }
        }
    }
}

private void PipeConnected(IAsyncResult e)
{
}

Mais il ne semble jamais attendre. Je reçois constamment l'exception suivante:

System.InvalidOperationException: pipe n'a pas encore été connecté.    à System.IO.Pipes.PipeStream.CheckWriteOperations ()    à System.IO.Pipes.PipeStream.WriteByte (valeur d'octet)    à PeachesObjectVisualizer.Visualizer.Show (IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)

Je pense que, après l'attente retourne tout devrait être prêt à aller.

Si j'utilise tout pipeServer.WaitForConnection () fonctionne très bien, mais suspendre l'application si le tuyau ne se connecte pas est pas une option.

Était-ce utile?

La solution

Vous devez appeler EndWaitForConnection .

var asyncResult = pipeServer.BeginWaitForConnection(PipeConnected, this);

if (asyncResult.AsyncWaitHandle.WaitOne(5000))
{
    pipeServer.EndWaitForConnection(asyncResult);

    // ...
}

Voir:. IAsyncResult design pattern

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top