Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by adam_2015 · May 02, 2016 at 05:17 AM · c#freezereadstreamreaderpipe

ReadLine from Named Pipe freezes Unity

Hi everyone.

I've got a problem which is that ReadLine method (StreamReader) freezes Unity when trying to read from a named pipe and that happens just after I start the game or to be more precise when I start to read.

I need to receive as well as send messages using the pipe to another process and ideally I would like to be able to listen to the pipe constantly and send a message at any time.

Here's my code:

 using UnityEngine;
 using System.Collections;
 using System.IO.Pipes;
 using System.IO;
 
 public class WEB_HANDLER : MonoBehaviour
 {
     private string pipeName
     {
         get
         {
             return "PIPE";
         }
     }
     private NamedPipeClientStream stream;
     private StreamWriter sw;
     private StreamReader sr;
 
 
     void Start()
     {
         //Starting the pipe
         Debug.LogFormat("[IPC] Creating new ClientStream. Pipe name: {0}", pipeName);
         stream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut);
 
         //Connecting to the pipe
         Debug.Log("[IPC] Connecting...");
         stream.Connect(120);
         Debug.Log("[IPC] Connected");
 
         //Initialising Readers/Writers
         Debug.Log("[IPC] Starting StreamReader");
         sr = new StreamReader(stream);
 
         Debug.Log("[IPC] Starting StreamWriter");
         sw = new StreamWriter(stream);
 
         //AutoFlush
         Debug.Log("[IPC] AutoFlush = true");
         sw.AutoFlush = true;
 
   
         Debug.Log("[IPC] Starting listening coroutine");
         StartCoroutine(Listen());
     }
 
     void Update()
     {
         //Sending messages to the pipe
         if (Input.GetKeyDown(KeyCode.Space))
         {
             Debug.Log("[IPC] Sending message to server");
             sw.WriteLine("Test message");
             Debug.Log("[IPC] Success");
         }
     }
 
     IEnumerator Listen()
     {
         while (true)
         {
                 string message = sr.ReadLine();
                 if (message.Length > 0) //If message is not empty then print it
                 {
                        Debug.Log(message);
                 }
                 yield return new WaitForEndOfFrame();
        }
 }

My guess is that I'm reading an empty string and there is no escape sequence in it so it keeps on reading nothing. If I'm right, how can I solve the problem?

Comment
Add comment · Show 4
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Toon_Werawat · May 02, 2016 at 09:03 AM 0
Share

Can you try this?

 IEnumerator Listen()
 {
     string message = string.Empty;
     while (sr.Peek >= 0)
     {
         message += sr.ReadLine();
         yield return null;
     }
     yield break;
 }
avatar image adam_2015 Toon_Werawat · May 02, 2016 at 10:15 AM 0
Share

It still freezes Unity.

avatar image Toon_Werawat · May 02, 2016 at 10:55 PM 0
Share

Hmm... $$anonymous$$aybe. Try not to use Coroutine at start or awake? While true too.

Try replace

 StartCoroutine(Listen());

To this

 Invoke("Listen",1f);

And this

 public string message = "";
 void Listen()
 {
     message = sr.ReadToEnd();;
 }
avatar image adam_2015 Toon_Werawat · May 03, 2016 at 12:46 PM 0
Share

Still freezes.

I think I'll try to make a separate thread for the interprocess communication because I will be able to make ReadLine read until the line escaping sequence without freezing the main thread.

However, I'm still waiting for any ideas that might help me.

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by adam_2015 · May 04, 2016 at 03:07 PM

I have finally made it work. As I said yesterday I tried to make it with a separate thread and it that solved the problem.

The following works as intended - the thread waits for event which is triggered (set) by changing messageTo variable which gets sent to another process. Then the thread keeps on reading until the message is not empty - thus we got some response from another process. And that repeats for until run (which is the condition of the main loop of the second thread) is set to false.

Here's my code:

 using UnityEngine;
 using System.IO.Pipes;
 using System.IO;
 using System.Threading;
 using System.ComponentModel;
 
 public class WEB_HANDLER : MonoBehaviour
 {
     private string pipeName
     {
         get
         {
             return "PIPE";
         }
     }
     private NamedPipeClientStream stream;
     private StreamWriter sw;
     private StreamReader sr;
 
     /// <summary>
     /// Thread for inter process communication
     /// </summary>
     private Thread interProc;
 
     /// <summary>
     /// When set tells thread to continue its work.
     /// </summary>
     private AutoResetEvent msgEvent;
 
     /// <summary>
     /// Must-have for get{} in messageTo
     /// </summary>
     private string tmpMessageTo;
 
     /// <summary>
     /// Message that will be sent to another process. Sets msgEvent automatically.
     /// </summary>
     private string messageTo
     {
         get
         {
             return tmpMessageTo; //Required so it doesn't cause infinite loop.
         }
         set
         {
             tmpMessageTo = value;
             msgEvent.Set(); //Setting event will cause second thread to continue its work.
         }
     }
     private string messageFrom;
 
     /// <summary>
     /// Should 2nd thread be still running?
     /// </summary>
     private volatile bool run = true;
 
     void Start()
     {
         msgEvent = new AutoResetEvent(false); //False means that it will not trigger the event when it's created.
     }
 
     void Update()
     {
         //Sending messages to the pipe
         if (Input.GetKeyDown(KeyCode.Space))
         {
             Debug.Log("[IPC] Changing message to server");
             messageTo = "message";
             Debug.Log("[IPC] Success");
         }
 
         //Starting the thread
         if (Input.GetKeyDown(KeyCode.LeftControl))
         {
             if (interProc != null && interProc.IsAlive)
             {
                 Debug.Log("[IPC] Thread is already running");
                 return;
             }
             Debug.Log("[LOCAL INFO] Starting new thread");
             interProc = new Thread(Listen);
             interProc.Start();
         }
 
         //Stooping thread
         if (Input.GetKeyDown(KeyCode.Escape))
         {
             Debug.Log("Stopping the thread");
             run = false;
             if (interProc != null)
             {
                 if (interProc.ThreadState != ThreadState.Aborted)
                     interProc.Abort();
             }
         }
     }
 
     /* --- SECOND THREAD ---*/
     /// <summary>
     /// Initialises writers/readers and the pipe
     /// </summary>
     void Initialise()
     {
         //Starting the pipe
         Debug.LogFormat("[IPC] Creating new ClientStream. Pipe name: {0}", pipeName);
         stream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut);
 
         //Connecting to the pipe
         Debug.Log("[IPC] Connecting...");
         try
         {
             stream.Connect(120);
         }
         catch (Win32Exception)
         {
             Debug.LogError("[IPC] Server not running");
             run = false;
             return;
         }
         Debug.Log("[IPC] Connected");
 
         //Initialising Readers/Writers
         Debug.Log("[IPC] Starting StreamReader");
         sr = new StreamReader(stream);
 
         Debug.Log("[IPC] Starting StreamWriter");
         sw = new StreamWriter(stream);
 
         //AutoFlush
         Debug.Log("[IPC] AutoFlush = true");
         sw.AutoFlush = true;
     }
     void Listen()
     {
         Initialise();
 
         while (run) //Main loop of the thread
         {
             messageFrom = "";
 
             Debug.Log("[2T-IPC] Waiting for change of message event");
             msgEvent.WaitOne(); //Waiting for event to be triggered (set)
 
             Debug.Log("[2T-IPC] Sending test message");
             sw.WriteLine(messageTo); //Writing command to the pipe
 
             Debug.Log("[2T-IPC] Waiting for pipe drain");
             stream.WaitForPipeDrain(); //Waiting for another process to read the command
 
             messageFrom = sr.ReadLine(); //Reading
             if (messageFrom.Length > 0)
             {
                 Debug.Log(messageFrom);
             }
         }
         Debug.Log("Finished");
     }
 
     /* --- UNITY'S THREAD --- */
     //The following should stop the thread on Editor and Standalone quit and also when the game object is destroyed.
     public void OnApplicationQuit()
     {
         run = false;
         if (interProc != null)
         {
             if (interProc.ThreadState != ThreadState.Aborted)
                 interProc.Abort();
         }
     }
 
     public void OnDestroy()
     {
         run = false;
         if (interProc != null)
         {
             if (interProc.ThreadState != ThreadState.Aborted)
                 interProc.Abort();
         }
     }
 }

So here's a little how-to-use of my code: 1. Attach the script to any game object 2. You have to have pipe server configured 3. Run the pipe server 4. Run the game 5. Press left control to run second thread 6. Press space to send the message

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Using Pipes/Streams Freezes Unity 1 Answer

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Renderer on object disabled after level reload 1 Answer

What could be freezing unity? 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges