using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;namespace MdiFrm
{
public partial class Form2 : Form
{ protected override void Dispose(bool disposing)
{
if (T != null) //当窗口已经被销毁。 结束该线程
{
T.Interrupt();
T = null;
}
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
public Form2()
{
InitializeComponent();
bln = true;
} Thread T;
bool bln;
private void Form2_Load(object sender, EventArgs e)
{
T = new Thread(new ThreadStart(Start));
T.IsBackground = true; //只有等窗口是主窗口的时候, 才会自动被运行时清理
T.Start();
} private void Start()
{
while (bln)
{
if (this.label1.InvokeRequired)
{
try
{
this.label1.Invoke(new EventHandler(UpdateText));
}
catch (ThreadInterruptedException ex) //此处会抛出线程被中断的一个异常
{
MessageBox.Show(bln.ToString());
}
}
Thread.Sleep(50);
}
} private void UpdateText(object sender, EventArgs e)
{
if (bln)
{
this.label1.Text += ".";
}
} private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
bln = false; //当窗口被关闭时让循环终止
}
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;namespace MdiFrm
{
public partial class Form2 : Form
{ protected override void Dispose(bool disposing)
{
if (T != null) //当窗口已经被销毁。 结束该线程
{
T.Interrupt();
T = null;
}
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
public Form2()
{
InitializeComponent();
bln = true;
} Thread T;
bool bln;
private void Form2_Load(object sender, EventArgs e)
{
T = new Thread(new ThreadStart(Start));
T.IsBackground = true; //只有等窗口是主窗口的时候, 才会自动被运行时清理
T.Start();
} private void Start()
{
while (bln)
{
if (this.label1.InvokeRequired)
{
try
{
this.label1.Invoke(new EventHandler(UpdateText));
}
catch (ThreadInterruptedException ex) //此处会抛出线程被中断的一个异常
{
MessageBox.Show(bln.ToString());
}
}
Thread.Sleep(50);
}
} private void UpdateText(object sender, EventArgs e)
{
if (bln)
{
this.label1.Text += ".";
}
} private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
bln = false; //当窗口被关闭时让循环终止
}
}
}
try
{
foreach (Process thisproc in Process.GetProcessesByName("你进程的名字"))
{
thisproc.Kill(); }
}
catch
{
}
wls12342004(青青子木)
该方法还没有去 catch (ThreadInterruptedException ex) //此处会抛出线程被中断的一个异常这个方法好吧。 你那样去遍历,个人觉得不是一个很好的办法。
但是在线程循环的地方那里, 必须要去catch这个异常, 不然就会抛出来。
目前就个人感觉。 该方法不是很好
你的线程每次运行之前就检查这个变量,如果发现为true, 就结束整个线程操作,
mythofcynthia(Blue)
你可以看到我在这里已经赋值为false了
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
bln = false; //当窗口被关闭时让循环终止
}
但是此处
this.label1.Invoke(new EventHandler(UpdateText));
同样会抛出线程终止的那个异常。 我猜可能是, 窗口的dispose来得比较快吧。
难道我的计算机是双核的原因?
设置成那个样子, 只对主线程, 有用。 如果我这个只是一个子窗口的, 他会等到主窗口被关掉的时候才会清理, 就像我注释中写的那样这样的话。 在改变text的那个地方, 同样会抛出异常。因为那个label已经被垃圾收集器销毁了