[...]
i've a groupBox with buttons which is disabled till i need to use them.. i
need to use them only when my streamReader is "stuck", meaning expecting
an
input.
i tried to check the ThreadState, but it won't help.
i noticed that when the ReadThread is waiting for input it's state is
Background | WaitSleepJoin, so i tried this code:
if (c_ThreadRead.ThreadState != System.Threading.ThreadState.Background)
{
groupBox1.Invoke((MethodInvoker)delegate {
groupBox1.Enabled = true; });
}
but it doesn't help, because if the threadState is Background only it
still
enables my groupBox.
The ThreadState enumeration is a flags enumeration. It seems unlikely to
me that it will ever _exactly_ equal ThreadState.Background.
Instead, you probably want something like:
groupBox1.Enabled = (c_ThreadRead.ThreadState &
ThreadState.WaitSleepJoin) == ThreadState.WaitSleepJoin;
Now, that said, I'm not exactly clear on where you're going to put this
code. It seems like the sort of thing that's in a polling loop, and
polling is generally something to be avoided.
One option would be enable the group just before reading, and then disable
it just after. That would work great if most of the time is spent waiting
on output. But if not, I think it would result in a fair amount of
flickering of the controls as they went back and forth between being
enabled and disabled.
Another alternative, and one that I think would probably work better,
would be to set a timer, and keep resetting it each time you successfully
read a line from your output. The timer interval would be some reasonable
timeout value, like a second or two, during which the control would remain
disabled. Only if the interval expires would you then enable the control.
That might look something like this (in your form class, using
System.Windows.Forms.Timer):
Timer _timer = new Timer();
void SomeMethodThatStartsEverything()
{
// do your process startup stuff, then
groupBox1.Enabled = false;
_timer.Interval = 1000;
_timer.Tick += TimerTickHandler;
_timer.Enabled = true;
}
void TimerTickHandler(object sender, EventArgs e)
{
_timer.Enabled = false;
groupBox1.Enabled = true;
}
void ReadStream(StreamReader sr)
{
string strLine;
while ((strLine = sr.ReadLine()) != null)
{
BeginInvoke((MethodInvoker)delegate
{
_timer.Enabled = false;
_timer.Enabled = true;
groupBox1.Enabled = false;
});
BeginInvoke((MethodInvoker)delegate
{ richTextBox1.Text += Environment.NewLine + strLine; });
}
}
Warning: I didn't compile that, so it might have some typos. Hopefully
you get the idea.
Also, note that I used BeginInvoke(). This isn't really necessary, but it
can potentially allow your code to run more efficiently by not forcing the
thread that's reading from the stream to keep yielding to your GUI
thread. Instead, the operations get added to the GUI thread's message
queue, to be processed whenever it next gets to run.
Pete