All articles(网络文学目录) All Pictures(图片目录) All Softwares(软件目录)

 
C#教程:删除线程

Writer: qq Article type: Programming skills(编程技巧) Time: 2014/7/11 9:23:32 Browse times: 281 Comment times: 0

C#教程:删除线程


Head photo

Go homepage
Upload pictures
Write articles

C#教程:删除线程

删除线程
线程的Abort方法用于永久地停止托管线程。调用Abort方法时,公共语言运行库在目标线程中引发ThreadAbortException,目标线程可捕捉此异常。一旦线程被中止,它将无法重新启动。
如果在应用程序中使用了多线程,辅助线程还没有执行完毕,在关闭窗体的时候必须要关闭辅助线程,否则会引发异常。
示例
线程的删除
下面的代码实现了删除线程t的功能。
namespace ThreadTest
{
public partial class Form1 : Form
{
private Thread t = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
t = new Thread(new ThreadStart(ThMethord));
t.Start();
}
public void ThMethord()
{
MessageBox.Show("线程启动");
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (t.IsAlive)
{
t.Abort();//关闭线程
}
}
}
}
完整程序代码如下:
★ ★★★★Form1.cs窗体代码文件完整程序代码★★★★★
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;
using System.Diagnostics;
using System.Net.Mail;
using System.IO;
namespace ThreadTest
{
public partial class Form1 : Form
{
private Thread t = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
t = new Thread(new ThreadStart(ThMethord));
t.Start();
}
public void ThMethord()
{
MessageBox.Show("线程启动!");
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (t.IsAlive)
{
t.Abort();
}
}
}
}
★ ★★★★Form1.Designer.cs窗体设计文件完整程序代码★★★★★
namespace ThreadTest
{
partial class Form1
{
///


/// 必需的设计器变量。
///

private System.ComponentModel.IContainer components = null;
///
/// 清理所有正在使用的资源。
///

/// 如果应释放托管资源,为 true;否则为 false。
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
///
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
///

private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(122, 191);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "启动线程";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(345, 287);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";




There are 0 records,
Comment:
Must be registered users to comment(必须是注册用户才能发表评论)

Disclaimer Privacy Policy About us Site Map
Copyright ©2011-
uuhomepage.com, Inc. All rights reserved.