0

I have simple chat app (Console application), that behaves like that (simplified):

while(true){
   var message = Console.ReadLine();
   SendMessage(message);
}

Sometimes server asks some questions, like: "Do you want to remove user1 from chat?". It appears in users Console as soon as it come from from server.

Console.WriteLine("Do you want to remove user1 from chat? y/n");
var answer = Console.ReadLine();
if(answer == "y") 
   RemoveUser();

But there is a problem: I'm calling ReadLine() method to get "message" first and usually later comes server message with ReadLine() that waits for "answer". So when user wants to answer "server question", he have to write something to "message" first (because this ReadLine was called first!)

So is there a way to tell computer that particular ReadLine() call is more important than others and it have to get data first? Can I change the order of getting data from user?

Piotrek
  • 10,919
  • 18
  • 73
  • 136
  • 3
    Code executes in the exact order that you write it. To change the order that it executes, just change the order of the code itself. Or are you describing a problem with multiple threads reading/writing the console at the same time? If that's the case then you might want to include that in your description and in your example. – David Nov 13 '15 at 18:36
  • 1
    You could have only one ReadLine. If there's a pending question, use it as an answer, otherwise send it as a chat message. – Pedro Villa Verde Nov 13 '15 at 18:39
  • 1
    This is a multi-threading issue. If you want to solve it then you cannot use Console.ReadLine() anymore. That's all technically possible but the only point in writing console mode apps is to keep the user interaction code simple. If you can't use the simple way anymore then it just stops making sense to still create a console mode app. – Hans Passant Nov 13 '15 at 18:52
  • Try using the following solution's [Console.Readline timeout](http://stackoverflow.com/a/18342182/1370984) – SILENT Nov 13 '15 at 19:05
  • Although I agree with the others that you are really stretching what a console app is really designed for, I could envision some kind of stack structure where you push functions that are supposed to get a `ReadLine` and when a ReadLine completes it returns the value to the top function on the stack. – Matt Burland Nov 13 '15 at 19:10
  • @MattBurland what about cancelling "ReadLine"? Can I disable all peding ReadLines? – Piotrek Nov 13 '15 at 19:20
  • @Ludwik11: Not without some hacking I think. – Matt Burland Nov 13 '15 at 19:21

0 Answers0