我如何杀死正在运行的线程? [英] How Can I Kill A Running Thread?
本文介绍了我如何杀死正在运行的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,
我创建了一个SplasScreen类来在一个小表单上显示处理...(或任何其他)gif。 (在这个网站上,我读了一篇关于此的文章,但我不记得是谁写的)当我调用ShowSplash方法时,它在屏幕上显示出一个闪光。我使用CloseSplash方法关闭它。通常,CloseSplash方法有效,但有时则不然。我不明白这是什么原因。这些是代码:
Hello,
I created a SplasScreen class to show "processing..."(or any other) gif on a little form. (In this site, I read an article about this but i can't remember who wrote it) When i call the ShowSplash method, it shows a splash on the screen. And i use the CloseSplash method to close it. Usually, the CloseSplash method works, but sometimes it doesn't. I don't understand what can be the reason of this. And those are the codes:
public class SplashScreen : Form
{
public Bitmap SImage {get; set;}
Thread t;
public void Flash()
{
PictureBox pb = new PictureBox();
pb.SizeMode = PictureBoxSizeMode.AutoSize;
pb.Image = SImage;
this.Width = pb.Width;
this.Height = pb.Height;
this.Controls.Add(pb);
this.TopMost = true;
this.StartPosition = FormStartPosition.CenterScreen;
this.FormBorderStyle = FormBorderStyle.None;
Application.Run(this);
}
public void sClose()
{
this.Close();
}
public void ShowSplash()
{
t = new Thread(new ThreadStart(Flash));
t.IsBackground = true;
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
public void CloseSplash()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(sClose));
}
}
}
以及使用它的示例:
And an example for using it:
SplashScreen sc = new SplashScreen();
sc.SImage = (Bitmap)Image.FromFile("processing.gif");
sc.ShowSplash();
//... codes codes codes...
sc.CloseSplash();
问候
Regards
推荐答案
你必须保持一个对你的正在运行的线程的引用,必须在类级别声明局部变量t
(可能有更好的名称)然后当你要关闭线程时你必须调用:
You have to keep a reference to your running thread, the local variablet
have to be declared at the class level (maybe with a better name) then when you want to close the thread you have to invoke:
if(t!= null && t.IsAlive()) //To make shore that the thread is running!
t.Abort();
这篇关于我如何杀死正在运行的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文