程序如下:
public void Polling()
{
try
{
...........
Thread[] mythread = new Thread[Count];
for (int i=0; i<Count;i ++)
{
mythread[i] = new Thread(new ParameterizedThreadStart(gatherOnlineTime));
....................
mythread[i].Start(obj);
}
}
catch
{
..............
}
}现在画面上有2个按钮 一个是执行这个函数开始多线程,另外一个是在运行的时候,点击"Cancel"按钮
终止线程的执行。
public void Polling()
{
try
{
...........
Thread[] mythread = new Thread[Count];
for (int i=0; i<Count;i ++)
{
mythread[i] = new Thread(new ParameterizedThreadStart(gatherOnlineTime));
....................
mythread[i].Start(obj);
}
}
catch
{
..............
}
}现在画面上有2个按钮 一个是执行这个函数开始多线程,另外一个是在运行的时候,点击"Cancel"按钮
终止线程的执行。
假如:
Thread[] myThread = new Thread[5]; private void AbortAliveThreads(Thread[] temp_Thread)
{
for (int i = 0; i < temp_Thread.Length; i++)
{
if (temp_Thread[i].IsAlive)
temp_Thread[i].Abort();
}
}未经测试代码,只供参考。
是必须的。问题是如何能够定位到 正在执行的线程阿,它已经运行了
而且点击另外一个按钮实现 上面代码里面已经写的就是点击"运行"这个按钮的时候
执行得函数,现在要点击 "Cancel"终止它们。
{
...........
Thread[] mythread = new Thread[Count];
for (int i=0; i <Count;i ++)
{
mythread[i] = new Thread(new ParameterizedThreadStart(gatherOnlineTime));
....................
mythread[i].Start(obj);
}
}
中,每次实例化类对象,再用list集合添加对象,最后在停止按钮事件中把list遍历,就能得到其中类对象中封装的线程。另一种办法就是用事件,先可以用类封装线程,然后在类中定义事件,在停止方法中触发该事件
private List<Thread> _myThreadList=new List<Thread>();
public void Polling()
{
try
{
...........
//Thread[] mythread = new Thread[Count];
for (int i=0; i <Count;i ++)
{
Thread mythread = new Thread(new ParameterizedThreadStart(gatherOnlineTime));
....................
mythread.Start(obj);
_myThreadList.Add(mythread);
}
}
catch
{
..............
}
}//停止按钮:
private void btn_Click(object sender, EventArgs e)
{
foreach(thread th in _myThreadList)
{
th.Abort();
}
_myThreadList.Clear();//移除所有线程
}
主要思想是:
在创建线程的时候将线程加到一个list中保存标示。在想停止所有线程的时候可以找到该线程list并停止所有线程。
for (int i=0; i <Count;i ++)
{
if (mythread[i] != null && mythread[i].IsAlive == true)
{
mythread[i].Abort();
}
}
Process[] allProcess = Process.GetProcesses();
foreach (Process p in allProcess)
{ if (p.ProcessName == "QQ")
{
//用循环先释放他所有的线程
for (int i = 0; i < p.Threads.Count; i++)
p.Threads[i].Dispose();
//不知道杀完美,最后再强行杀一次吧,你是小强也杀掉了吧
p.Kill(); break;
} }