I have the following code which is working but it is very dirty. Actually the code is just fine except the part I added: a pause and a stop button. I’m new to c# so any help would be apreciated.
private void pause_button_Click(object sender, EventArgs e)
{
start = false; pause = true; stop = false;
guiUpdate();
PauseEvent.Reset();
}
private void stop_button_Click(object sender, EventArgs e)
{
if (pause == true)
{
PauseEvent.Set();
pause = false;
this.start_button.Click -= new System.EventHandler(this.resume_button_Click);
}
start = false; stop = true;
}
private int activeThreads = 0;
private Thread thread;
private void DoWork(object sender)
{
string line = null;
ereader = new StreamReader(MY_LIST);
do
{
lock (ereader)
{
PauseEvent.WaitOne();
line = ereader.ReadLine();
}
//
//other commands for processing & building the argument
//
lock (signal)
{
++activeThreads;
}
thread = new Thread(new ParameterizedThreadStart(
o =>
{
processit((object)o);
lock (signal)
{
--activeThreads;
Monitor.Pulse(signal);
}
}));
thread.Start(argument);
lock (signal)
{
while (activeThreads > maxthreads)
Monitor.Wait(signal);
}
lock (signal)
{
if (!start)
{
showwaiting(true);//shows an animated gif with a "please wait" msg
while (activeThreads > 0)
Monitor.Wait(signal);
showwaiting(false);
if (stop == true)
{
this._BackgroundWorker.CancelAsync();
break;
}
}
}
}
while (ereader.Peek() != -1);
showwaiting(true);
lock (signal)
{
while (activeThreads > 0)
Monitor.Wait(signal);
}
showwaiting(false);
}
private void _BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
start = false; stop = true;
guiUpdate();
}
what exactly can I do to avoid those duplicate commands inside and outside the loop ?
Mentioned in the question comments are suggestions about code practice changes.
== trueor== falsewhen checking a boolean variable in a condition. (Jeff)I would also add:
showwaitinguseShowWaiting).For your small loops, you don’t really need to optimize them out though there is more than a simple loop. So you could refactor them to a separate method along with all the code that is the same:
Note that it is fine for the same thread to lock on a monitor that it previously acquired. This is a fast operation since the thread already owns the lock. You can then call this method from both places.