在C#中如何关闭线程
来源:百度知道 编辑:UC知道 时间:2024/05/29 23:37:15
在另一个button2中无法调用在button1中已经实例化的线程。要怎么办?
江湖少侠举的例子,我试过了,
public Thread thread;
private void button1_Click(object sender, EventArgs e)
{
thread = new Thread(new ThreadStart(Method));
thread.Start();
}
private void Method()
{
textBox1.Text = "sa";
}
private void button2_Click(object sender, EventArgs e)
{
thread.Abort();
}
结果在thread.abort()上有“未将对象引用设置到对象的实例”的提示。
启动时记住此thread.
调用thread.Abort();
*********************************************
补充:
看来你没理解局部变量和字段是什么。
class XXX
{
Thread thread;
void button1_Click(object o,EventArgs e)
{
thread = new Thread(new ThreadStart(Method)); }
void button2_Click(object o,EventArgs e)
{
thread.Abort();
}
}
线程没有实例化这个概念,只有启动,停止,暂停等方法, 每个线程都会有一个名字,调用每个线程的 Abort() 方法就可以停止该线程了。
补充:
你的变量名是在哪里声明的? 如果要在另一个按钮事件中也能访问,必须声明为类的变量。
private void display()
{
while (ff == true)
{
}
}
void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "开始监控")
{
ff=true;
Thread a = new Thread(new ThreadStart(display));
a.Start();
button1.Text = "停止监控";
}
el