我有以下代码正在运行,但它很脏。实际上代码很好,除了我添加的部分:暂停和停止按钮。我是 c# 的新手,所以任何帮助都会受到赞赏。
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();
}
我究竟能做些什么来避免循环内外的重复命令?