在form上有button1和button2,button1事件中有如下代码,应该如何实现单击button2,来立即终止button1线程
privatevoidbutton1_Click(objectsender,EventArgse){Threadmythread=newThread(newThreadS...
private void button1_Click(object sender, EventArgs e)
{
Thread mythread = new Thread(new ThreadStart(upgrade));
mythread.IsBackground = true;
mythread.Start();
} 展开
{
Thread mythread = new Thread(new ThreadStart(upgrade));
mythread.IsBackground = true;
mythread.Start();
} 展开
2个回答
展开全部
方法1:根据现有代码
bool ifStop = false;
private void button2_Click(object sender, EventArgs e)
{
ifStop= true;
}
upgrade函数
while(!ifStop)
{
......
}
方法2 改变button1中Thread申明
Thread mythread;
private void button1_Click(object sender, EventArgs e)
{
mythread = new Thread(new ThreadStart(upgrade));
mythread.IsBackground = true;
mythread.Start();
}
private void button1_Click(object sender, EventArgs e)
{
if(mythread != null && mythread.isAlive)
mythread.abort();
}
bool ifStop = false;
private void button2_Click(object sender, EventArgs e)
{
ifStop= true;
}
upgrade函数
while(!ifStop)
{
......
}
方法2 改变button1中Thread申明
Thread mythread;
private void button1_Click(object sender, EventArgs e)
{
mythread = new Thread(new ThreadStart(upgrade));
mythread.IsBackground = true;
mythread.Start();
}
private void button1_Click(object sender, EventArgs e)
{
if(mythread != null && mythread.isAlive)
mythread.abort();
}
追问
方法一中upgrade()都执行完了,我没说清楚,upgrade()耗时太长我才要终结的,方法二可以。
麻烦再问一下,我写的upgrade()作用是:文件的copy,在copy到指定文件夹时,我对将要被覆盖的文件作了个备份,放到临时文件夹中了。然后又写了个load(),,过程是:我要实现A目录move到B目录,先把B目录move到C目录,由于A到B耗时太长,做了一段时间我取消了,然后要把C在move回B,为什么老是报错说某个文件在被访问
追答
文件被访问,也就是说你在移动的时候某个文件被打开或者更改,你恰好停止了线程,以至于这些打开的文件被占用了,停止线程可是不管你是否关闭了文件handle,因此你在停止线程前得先清理一下打开的文件handle
展开全部
把button1的线程设置成全局的,然后在button2中就可以调用那个线程将其关闭了
Thread mythread;
public void button1_Click(object sender, EventArgs e)
{
mythread = new Thread(new ThreadStart(upgrade));
mythread.IsBackground = true;
mythread.Start();
}
Thread mythread;
public void button1_Click(object sender, EventArgs e)
{
mythread = new Thread(new ThreadStart(upgrade));
mythread.IsBackground = true;
mythread.Start();
}
追问
麻烦再问一下,我写的upgrade()作用是:文件的copy,在copy到指定文件夹时,我对将要被覆盖的文件作了个备份,放到临时文件夹中了。然后又写了个load(),,过程是:我要实现A目录move到B目录,先把B目录move到C目录,由于A到B耗时太长,做了一段时间我取消了,然后要把C在move回B,为什么老是报错说某个文件在被访问
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询