Reputation: 26
My console application exits before code has finished (after executing/trying to execute lines such as "Console.WriteLine" or "int i = 0")
I've added some breakpoints to see which line is the last to be executed before the program exits. On the first few attempts, the program exits after/when trying to execute the following line:
Console.WriteLine($"Online users to chat with ({users.Length} total):");
Then, I tried to get the value of the string in the Console.WriteLine brackets using the Immediate window- which worked. I pressed F10 to proceed to the next line, and it did- successfully printing the given parameter. But then, after pressing F10 the program closed itself, when the highlighted part was "int i = 0":
for (int i = 0; i < users.Length; i++)
Here is the code, I've added comments on all the lines the program closed so far:
public static void Main()
{
client = new WebClient();
messages = null;
try
{
LocalhostServer.Start("Chat");
// Starts a server with System.Net.HttpListener. The prefix added is: http://localhost:<port>/Chat/
}
catch { }
LocalhostServer.RecievedRequest += LocalhostServer_RecievedRequest;
Console.WriteLine("Enter your name:");
name = Console.ReadLine();
// closed here^^ after adding a new breakpoint to this line, makes no sense to me
try
{
client.DownloadString(new Uri(Url + "AddUser?name=" + name));
// Url is a static string which is set to: "http://localhost:<port>/Chat/"
}
catch { }
ShowOnlineUsers();
}
private static async void ShowOnlineUsers()
{
try
{
thread = new Thread(CheckIfChatStarted);
thread.Start();
Console.Clear();
string[] users = (await DownloadStringUntilSuccess(Url + "GetOnlineUsers")).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
// closed here^^ after adding a new breakpoint to this line
Console.WriteLine($"Online users to chat with ({users.Length} total):"); // closed here
for (int i = 0; i < users.Length; i++) // closed here on "int i = 0;"
{
Console.WriteLine($"{i + 1}. {users[i]}");
}
Console.WriteLine("\nEnter user number to chat with:");
recipient = users[int.Parse(Console.ReadLine()) - 1];
}
catch (Exception ex)
{ // hasn't reached the breakpoint on that bracket
}
client.DownloadString(new Uri(Url + "StartChat?name=" + name + "&recipient=" + recipient));
}
I have no idea why it happens... Many thanks in advance to anyone's attempt to help!
P.S- Can this be caused due to a Console.Clear/Console.WriteLine commands being executed in a background thread while the main thread is waiting for user's input (Console.ReadLine)? If so, is there any solution/work-around?
Upvotes: 1
Views: 366