我有Thread
的包装类:
public class ThreadWrapper
{
private bool Terminated = false;
private string threadName;
private Thread _thread;
public bool needToTerminate
{
get
{
lock (this)
{
return Terminated;
}
}
}
public string ThreadName
{
get
{
lock (this)
{
return threadName;
}
}
}
// for override constructor in derived classes
public ThreadWrapper()
{
}
public ThreadWrapper(string threadName)
{
this.threadName = threadName;
}
public virtual void Run()
{
}
public virtual void Terminate()
{
lock (this)
{
Terminated = true;
}
}
public void Start()
{
lock (this)
{
if (_thread == null)
{
_thread = new Thread(Run);
_thread.Start();
}
}
}
}
然后我从ThreadWrapper
创建派生类:
public delegate void ProcessMessageDelegate(string message);
public class Reader : ThreadWrapper
{
private ProcessMessageDelegate ProcessMessage;
public Reader(ProcessMessageDelegate processMessage)
: base()
{
this.ProcessMessage = processMessage;
}
public override void Run()
{
// Do something
}
}
我也有两个按钮的表格。开始线程的第一个按钮,第二个按钮用于"自我终止"线程。
public partial class MainForm : Form
{
private MyReader Reader;
public MainForm()
{
InitializeComponent();
}
// real method for delegate
private void ProcessMessage(string message)
{
// add line to RichEdit
this.AddSpRRecordLog(message);
}
private void buttonRunTest_Click(object sender, EventArgs e)
{
if (MyReader == null)
{
MessageBox.Show("Wrong!");
return;
}
MyReader.Start();
}
private void buttonStopTest_Click(object sender, EventArgs e)
{
if (MyReader == null)
{
MessageBox.Show("Wrong!");
return;
}
MyReader.Terminate();
}
private void MainForm_Load(object sender, EventArgs e)
{
Reader MyReader = new Reader(new ProcessMessageDelegate(ProcessMessage));
}
如果我使用这种方式(在MyReader
事件上创建FormLoad
) - MyReader
无法创建。如果我在buttonRunTest_Click
创建了阅读,那么一切正常,但在这种情况下,我无法终止MyReader
。
答案 0 :(得分:4)
这声明了一个名为MyReader
的局部变量,它隐藏了MyReader
字段:
private void MainForm_Load(object sender, EventArgs e)
{
Reader MyReader = new Reader(new ProcessMessageDelegate(ProcessMessage));
}
相反,只需指定字段:
private void MainForm_Load(object sender, EventArgs e)
{
MyReader = new Reader(new ProcessMessageDelegate(ProcessMessage));
}
(顺便说一下,这不是传统意义上的全局变量 - 如果创建了MainForm
的另一个实例,它将拥有自己独立的MyReader
字段