For my textbased/window game, I have a command called "/sleep". This asks the player how many hours he would like to sleep, and he can enter in an amount. After each hour, it should output to the output screen (txtOutput) saying "1 hour has passed," etc. Right now, there's a long wait til it outputs anything, and when it does, it outputs more than one message. Obviously, this is because I'm running this under one thread. I need a second thread to make this work, I believe. Since I'm new to threads, I'm hoping you can tell me what I'm doing wrong here.
After player types in /sleep, bHoursToSleep's boolean state is turned to true. Next, the program will notice bHoursToSleep is true, so it should do the following game state:
// get boolean states
if (bHoursToSleep == true)
{
hours = int.Parse(sBuffer);
ThreadStart hoursThread = new ThreadStart(sleepingTime);
Thread sleepThread = new Thread(hoursThread);
sleepThread.Name = "Sleeping Thread";
sleepThread.Start();
}
ThreadStart calls the sleepingTime() method.
public void sleepingTime()
{
try
{
for (int i = 0; i < hours; i++)
{
AddText(i + " hour(s) pass by.");
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
bHoursToSleep = false; // turns off boolean state
}
Error during runtime, pointing at: Application.Run(new frmMain());
Illegal cross-thread operation: Control 'txtOutput' accessed from a thread
other than the thread it was created on.\r\nStack trace where the illegal operation occurred was:\r\n\r\n\tat System.Windows.Forms.Control.get_Handle()
\r\n\tat System.Windows.Forms.RichTextBox.ForceHandleCreate()\r\n\tat
System.Windows.Forms.RichTextBox.get_Text()\r\n\tat
The_Nral_Prophecies.frmMain.AddText(String)\r\n\tat The_Nral_Prophecies.frmMain.sleepingTime()\r\n\tat
System.Threading._Thread.ThreadStart_Context(Object)\r\n\tat
System.Threading.ExecutionContext.Run(ExecutionContext, ContextCallback,
Object, StackCrawlMark&)\r\n\tat System.Threading._Thread.ThreadStart()\r\n\"
I tried making this clear as much as possible. Please let me know with some code examples too since I seem to better understand them. Thanks in advanced.
Phil